Templating in practice : Other helpers
Overview
Symfony offers a few helpers to quickly manipulate text.
Text helpers
truncate_text()
For no-wrap width-limited blocks - for instance in select tags - you may need to allow a maximum number of characters and truncate the rest if needed. To that purpose, you should use the truncate_text helper:
<?php use_helper('Text') ?>
<?php echo truncate_text($text, $length , $truncate_string = '...') ?>
// For instance, if $text="You can't stop me ! You can't stop me ! You can't stop me ! You can't stop me !"
<?php echo truncate_text($text, 30) ?>
// will be output as
You can't stop me ! You can't ...
excerpt_text()
Websites that offer full-text search need to show where the text was found. This is another type of truncation, and the helper that does it is excerpt_text:
<?php echo excerpt_text($text, $sentence, $radius = 100 , $truncate_string = '...') ?>
// For instance, if $text="Finding a word in an ocean of text can sometimes be a real pain."
<?php echo excerpt_text($text, 'ocean', 10) ?>
// will be output as
...ord in an ocean of text c...
highlight_text()
Maybe you need to highlight a sentence in a text:
<?php echo highlight_text($text, $sentence, [$highlighter]) ?>
//$highlighter is the class 'highlight' by default
// For instance, if $text='The best PHP framework is symfony'
<?php echo highlight_text($text, 'symfony') ?>
// will be output as
The best PHP framework is <span class="highlight">symfony</span>
simple_format_text()
Or maybe you need to format an ASCII text to HTML:
<?php echo simple_format_text($text) ?>
simple_format_text surrounds paragraphs with <p>...</p> tags, and converts line breaks into <br />. Two consecutive newlines (\n\n) are considered as a paragraph, one newline (\n) is considered a line break, three or more consecutive newlines are turned into two newlines. It might be useful to display, for instance, data entered by the user in a textarea.
auto_link_text()
Another useful helper finds all the URLs in a text and turns them into hyperlinks
<?php echo auto_link_text('my homesite is www.mysite.com') ?>
// will generate in HTML
my homesite is <a href="http://www.mysite.com">www.mysite.com</a>
|