tags:

views:

592

answers:

1

I'm trying to find a way to wrap a long headline after a specific number of words, based on the total character count of the headline. My purpose is to make the bottom line of the wrapped text longer than the top line to increase readability.

I'd like to use Smarty to find the character count of the headline, then decide how long to make the first line based on the default font size and the width of the containing element. But I'm not a coder and don't know the best way to make arrays, foreach loops, iteration counts, and other stuff that's probably necessary to pull this off.

I'm basically trying to:

1) Find the total character count of the headline using {$item.name|count_characters:true}

2) If the total character count is between 60 and 100 characters, add a br tag at the end of the first word that ends past 30 characters.

Anyone who's up for the challenge would help me out a lot. Thanks!

+1  A: 

I believe that you can do this with register_modifier(). Basically, you write a php function to insert the tag, then register it as a modifier. After you've done that, use it in smarty like you would other modifiers, ie:

{$variable|break_title}

In general, it's better not to do complex formatting within smarty templates. Things are cleanest the closer your templates are to vanilla html.

Possible implementation:

function break_title($title) {
   return wordwrap($title, 59, '<br />\n');
}

/* later */
$smarty->register_modifier('break_title', 'break_title');

If you want to take font size into account, you can set a global configuration variable indicating the number of characters to break after.

EDIT: As the commentor mentions, if there is an existing php function that does what you want, you can access it without registering the function:

{$variable|wordwrap:59:"<br />\n"}
Dana the Sane
Or pipe it directly to wordwrap {$variable|wordwrap:59:"<br /\n"}
Bob Fanger
Thanks, I've updated my answer.
Dana the Sane