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.

See also register_modifier(), register_function(), Extending Smarty with plugins and modifiers,

capitalize

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

Parameter PositionTypeRequiredDefaultDescription
1booleanNofalseThis determines whether or not words with digits will be uppercased

Example 5-2. capitalize

<?php

$smarty
->assign('articleTitle''next x-men film, x3, delayed.');

?>

Where template 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.

See also lower and upper

© Copyright 2003-2023 www.php-editors.com. The ultimate PHP Editor and PHP IDE site.