Smarty: Variable Modifiers

Chapter 5. Variable Modifiers


Variable modifiers can be applied to variables, custom functions or strings. To apply a modifier, specify the value followed by the | (pipe) and the modifier name. A modifier may accept additional parameters that affect its behavior. These parameters follow the modifer name and are separated by : (colon).

Example 5-1. modifier example
{* apply modifier to a variable *}
{$title|upper}
{* modifier with parameters *}
{$title|truncate:40:"..."}

{* apply modifier to a function parameter *}
{html_table loop=$myvar|upper}
{* with parameters *}
{html_table loop=$myvar|truncate:40:"..."}

{* apply modifier to literal string *}
{"foobar"|upper}

{* using date_format to format the current date *}
{$smarty.now|date_format:"%Y/%m/%d"}

{* apply modifier to a custom function *}
{mailto|upper address="me@domain.dom"}

If you apply a modifier to an array variable instead of a single value variable, the modifier will be applied to every value in that array. If you really want the modifier to work on an entire array as a value, you must prepend the modifier name with an @ symbol like so: {$articleTitle|@count} (this will print out the number of elements in the $articleTitle array.)

Modifiers can be autoloaded from your $plugins_dir (also see: Naming Conventions) or can be registered explicitely (see: register_modifier). Additionally all php-functions can be used as modifiers implicitly. (The @count-example above actually uses php's count-function and not a smarty-modifier). Using php-functions as modifiers has two little pitfalls: First: Sometimes the order of the function-parameters is not the desirable one ({"%2.f"|sprintf:$float} actually works, but asks for the more intuitive. For example:{$float|string_format:"%2.f"} that is provided by the Smarty distribution). Second: with $security turned on all php-functions that are to be used as modifiers have to be declared trusted in the $security_settings['MODIFIER_FUNCS']-array.

capitalize

Parameter Position Type Required Default Description
1 boolean No false This determines whether or not words with digits will be uppercased

This is used to capitalize the first letter of all words in a variable.

Example 5-2. capitalize
<?php

$smarty
= new Smarty;
$smarty->assign('articleTitle', 'next x-men film, x3, delayed.');
$smarty->display('index.tpl');

?>

Where index.tpl is:

{$articleTitle}
{$articleTitle|capitalize}
{$articleTitle|capitalize:true}

This will output:

next x-men film, x3, delayed.
Next X-Men Film, x3, Delayed.
Next X-Men Film, X3, Delayed.

count_characters

Parameter Position Type Required Default Description
1 boolean No false This determines whether or not to include whitespace characters in the count.

This is used to count the number of characters in a variable.

Example 5-3. count_characters
<?php

$smarty
= new Smarty;
$smarty->assign('articleTitle', 'Cold Wave Linked to Temperatures.');
$smarty->display('index.tpl');

?>

Where index.tpl is:

{$articleTitle}
{$articleTitle|count_characters}
{$articleTitle|count_characters:true}

This will output:

Cold Wave Linked to Temperatures.
29
33

cat

Parameter Position Type Required cat Description
1 string No empty This value to catenate to the given variable.

This value is concatenated to the given variable.

Example 5-4. cat
<?php    
$smarty
= new Smarty;
$smarty->assign('articleTitle', "Psychics predict world didn't end");
$smarty->display('index.tpl');
?>

Where index.tpl is:

{$articleTitle|cat:" yesterday."}

This will output:

Psychics predict world didn't end yesterday.

count_paragraphs

This is used to count the number of paragraphs in a variable.

Example 5-5. count_paragraphs
<?php
$smarty
= new Smarty;
$smarty->assign('articleTitle', "War Dims Hope for Peace. Child's Death Ruins
Couple's Holiday.\n\nMan is Fatally Slain. Death Causes Loneliness, Feeling of Isolation."
);
$smarty->display('index.tpl');
?>

Where index.tpl is:

{$articleTitle}
{$articleTitle|count_paragraphs}

This will output:

War Dims Hope for Peace. Child's Death Ruins Couple's Holiday.

Man is Fatally Slain. Death Causes Loneliness, Feeling of Isolation.
2

count_sentences

This is used to count the number of sentences in a variable.

Example 5-6. count_sentences
<?php
    
$smarty
= new Smarty;
$smarty->assign('articleTitle', 'Two Soviet Ships Collide - One Dies. Enraged Cow Injures Farmer with Axe.');
$smarty->display('index.tpl');

?>

Where index.tpl is:

{$articleTitle}
{$articleTitle|count_sentences}

This will output:

Two Soviet Ships Collide - One Dies. Enraged Cow Injures Farmer with Axe.
2

count_words

This is used to count the number of words in a variable.

Example 5-7. count_words
<?php
    
$smarty
= new Smarty;
$smarty->assign('articleTitle', 'Dealers Will Hear Car Talk at Noon.');
$smarty->display('index.tpl');

?>

Where index.tpl is:

{$articleTitle}
{$articleTitle|count_words}

This will output:

Dealers Will Hear Car Talk at Noon.
7

date_format

Parameter Position Type Required Default Description
1 string No %b %e, %Y This is the format for the outputted date.
2 string No n/a This is the default date if the input is empty.

This formats a date and time into the given strftime() format. Dates can be passed to Smarty as unix timestamps, mysql timestamps or any string made up of month day year (parsable by strtotime). Designers can then use date_format to have complete control of the formatting of the date. If the date passed to date_format is empty and a second parameter is passed, that will be used as the date to format.

Example 5-8. date_format
<?php
    
$smarty
= new Smarty;
$smarty->assign('yesterday', strtotime('-1 day'));
$smarty->display('index.tpl');
    
?>

Where index.tpl is:

{$smarty.now|date_format}
{$smarty.now|date_format:"%A, %B %e, %Y"}
{$smarty.now|date_format:"%H:%M:%S"}
{$yesterday|date_format}
{$yesterday|date_format:"%A, %B %e, %Y"}
{$yesterday|date_format:"%H:%M:%S"}

This will output:

Feb 6, 2001
Tuesday, February 6, 2001
14:33:00
Feb 5, 2001
Monday, February 5, 2001
14:33:00

date_format conversion specifiers:

  • %a - abbreviated weekday name according to the current locale
  • %A - full weekday name according to the current locale
  • %b - abbreviated month name according to the current locale
  • %B - full month name according to the current locale
  • %c - preferred date and time representation for the current locale
  • %C - century number (the year divided by 100 and truncated to an integer, range 00 to 99)
  • %d - day of the month as a decimal number (range 00 to 31)
  • %D - same as %m/%d/%y
  • %e - day of the month as a decimal number, a single digit is preceded by a space (range 1 to 31)
  • %g - Week-based year within century [00,99]
  • %G - Week-based year, including the century [0000,9999]
  • %h - same as %b
  • %H - hour as a decimal number using a 24-hour clock (range 00 to 23)
  • %I - hour as a decimal number using a 12-hour clock (range 01 to 12)
  • %j - day of the year as a decimal number (range 001 to 366)
  • %k - Hour (24-hour clock) single digits are preceded by a blank. (range 0 to 23)
  • %l - hour as a decimal number using a 12-hour clock, single digits preceeded by a space (range 1 to 12)
  • %m - month as a decimal number (range 01 to 12)
  • %M - minute as a decimal number
  • %n - newline character
  • %p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale
  • %r - time in a.m. and p.m. notation
  • %R - time in 24 hour notation
  • %S - second as a decimal number
  • %t - tab character
  • %T - current time, equal to %H:%M:%S
  • %u - weekday as a decimal number [1,7], with 1 representing Monday
  • %U - week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week
  • %V - The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week.
  • %w - day of the week as a decimal, Sunday being 0
  • %W - week number of the current year as a decimal number, starting with the first Monday as the first day of the first week
  • %x - preferred date representation for the current locale without the time
  • %X - preferred time representation for the current locale without the date
  • %y - year as a decimal number without a century (range 00 to 99)
  • %Y - year as a decimal number including the century
  • %Z - time zone or name or abbreviation
  • %% - a literal `%' character

Programmers note: date_format is essentially a wrapper to PHP's strftime() function. You may have more or less conversion specifiers available depending on your system's strftime() function where PHP was compiled. Check your system's manpage for a full list of valid specifiers.

default

Parameter Position Type Required Default Description
1 string No empty This is the default value to output if the variable is empty.

This is used to set a default value for a variable. If the variable is empty or unset, the given default value is printed instead. Default takes one argument.

Example 5-9. default
<?php

$smarty
= new Smarty;
$smarty->assign('articleTitle', 'Dealers Will Hear Car Talk at Noon.');
$smarty->display('index.tpl');

?>

Where index.tpl is:

{$articleTitle|default:"no title"}
{$myTitle|default:"no title"}

This will output:

Dealers Will Hear Car Talk at Noon.
no title

escape

Parameter Position Type Required Possible Values Default Description
1 string No html,htmlall,url,quotes,hex,hexentity,javascript html This is the escape format to use.

This is used to html escape, url escape, escape single quotes on a variable not already escaped, hex escape, hexentity or javascript escape. By default, the variable is html escaped.

Example 5-10. escape
<?php
    
$smarty
= new Smarty;
$smarty->assign('articleTitle', "'Stiff Opposition Expected to Casketless Funeral Plan'");
$smarty->display('index.tpl');
    
?>

Where index.tpl is:

{$articleTitle}
{$articleTitle|escape}
{$articleTitle|escape:"html"} {* escapes & " ' < > *}
{$articleTitle|escape:"htmlall"} {* escapes ALL html entities *}
{$articleTitle|escape:"url"}
{$articleTitle|escape:"quotes"}
<a class="blue" HREF="p_mailto:{$EmailAddress|escape:"hex"}">{$EmailAddress|escape:"hexentity"}</a>

This will output:

'Stiff Opposition Expected to Casketless Funeral Plan'
&#039;Stiff Opposition Expected to Casketless Funeral Plan&#039;
&#039;Stiff Opposition Expected to Casketless Funeral Plan&#039;
&#039;Stiff Opposition Expected to Casketless Funeral Plan&#039;
%27Stiff+Opposition+Expected+to+Casketless+Funeral+Plan%27
\'Stiff Opposition Expected to Casketless Funeral Plan\'
<a class="blue" HREF="p_mailto:%62%6f%62%40%6d%65%2e%6e%65%74">&#x62;&#x6f;&#x62;&#x40;&#x6d;&#x65;&#x2e;&#x6e;&#x65;&#x74;</a>

indent

Parameter Position Type Required Default Description
1 integer No 4 This determines how many characters to indent to.
2 string No (one space) This is the character used to indent with.

This indents a string at each line, default is 4. As an optional parameter, you can specify the number of characters to indent. As an optional second parameter, you can specify the character to use to indent with. (Use "\t" for tabs.)

Example 5-11. indent
<?php
    
$smarty
= new Smarty;
$smarty->assign('articleTitle', 'NJ judge to rule on nude beach.
Sun or rain expected today, dark tonight.
Statistics show that teen pregnancy drops off significantly after 25.'
);
$smarty->display('index.tpl');

?>

Where index.tpl is:

{$articleTitle}

{$articleTitle|indent}

{$articleTitle|indent:10}

{$articleTitle|indent:1:"\t"}

this will output:

NJ judge to rule on nude beach.
Sun or rain expected today, dark tonight.
Statistics show that teen pregnancy drops off significantly after 25.

NJ judge to rule on nude beach.
Sun or rain expected today, dark tonight.
Statistics show that teen pregnancy drops off significantly after 25.

NJ judge to rule on nude beach.
Sun or rain expected today, dark tonight.
Statistics show that teen pregnancy drops off significantly after 25.

NJ judge to rule on nude beach.
Sun or rain expected today, dark tonight.
Statistics show that teen pregnancy drops off significantly after 25.