Page 1 of 1

[SOLVED] Smarty Truncate Problem

Posted: Sun Jul 08, 2012 10:53 pm
by beherenow_uk
So this is a strange one...

I have a news summary that looks like this:

Code: Select all

{if $entry->content}
<div class="newstext">
{eval var=$entry->content|truncate:100}
<p><a class="readmore" href="{$entry->moreurl}">read more &rarr;</a></p>
</div>
{/if}
My <p> tags are inside the article, which outputs:

Code: Select all

<div class="newstext">
<p>As part of our commitment to ensure you reach your personal Health Goals, (company name) have...
<p><a class="readmore" href="#thelink">read more &rarr;</a></p>
</div>
Problem is, as you can see the trailing </p> is truncated too, meaning that the page doesn't validate! And I potentially will have display issues too.

Anybody have an idea how to make it NOT truncate the trailing </p> tag? I've looked everywhere!

Thanks in advance.

Re: Smarty Truncate Problem

Posted: Mon Jul 09, 2012 12:37 am
by Dr.CSS
The problem is not knowing where the <p> is going to end, if it has 2 paragraphs or ? but you could add </p> after the summary truncate call in the summary template...

Re: Smarty Truncate Problem

Posted: Mon Jul 09, 2012 2:13 am
by calguy1000
The summarize, and truncate modifiers are designed to work with text, not html. They count characters, or words... they don't care about what markup is there.

If you want to display the first N characters of 'text' you have to convert the html to text first.

|strip_tags|truncate

should do the trick.

Re: Smarty Truncate Problem

Posted: Mon Jul 09, 2012 10:22 pm
by beherenow_uk
Perfect...

Code: Select all

|strip_tags|truncate 
Worked a treat! Thank you.

Re: [SOLVED] Smarty Truncate Problem

Posted: Thu Jul 12, 2012 12:32 am
by applejack
If you want to truncate just the first sentence you can use the modifier below which I recently came across. Just copy the code and upload to /lib/smarty/plugins name it modifier.first_sentence.php

In you smarty tag just use |first_sentence

Calguy how about adding this as one the core tags as it is pretty useful.

Code: Select all

<?php 
/** 
 * Smarty plugin 
 * @package Smarty 
 * @subpackage plugins 
 */ 


/** 
 * Smarty first_sentence modifier plugin 
 * 
 * Type:     modifier
 * Name:     first_sentence 
 * Purpose:  trim a string to the first sentence 
 * @link http://www.phpinsider.com/smarty-forum/viewtopic.php?t=10170 
 * @author   Boots 
 * @param string 
 * @return integer 
 */ 
function smarty_modifier_first_sentence($string) 
{ 
    // find periods with a word before but not after. 
    preg_match('/^.*[^\s]\.(?!\w)/U', $string, $match); 
    return $match[0]; 
} 

/* vim: set expandtab: */ 

?>

Re: [SOLVED] Smarty Truncate Problem

Posted: Sat Jul 14, 2012 7:37 am
by Rolf
Nice one, Applejack!