Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smarty : substr a variable

Tags:

smarty

How can I print the first n characters of a smarty variable, e.g. the first 30 characters of {$var}?

like image 763
Rami Dabain Avatar asked Dec 01 '10 14:12

Rami Dabain


2 Answers

Use the PHP function:

{$var|substr:0:30}

or mb_substr for UTF-8 variables:

{$var|mb_substr:0:30}

Quoting from the Variable Modifiers section of the documentation:

All php-functions can be used as modifiers implicitly, as demonstrated in the example above. However, using php-functions as modifiers has two little pitfalls:

  • First - sometimes the order of the function-parameters is not the desirable one. Formatting $foo with {"%2.f"|sprintf:$foo} actually works, but asks for the more intuitive, like {$foo|string_format:"%2.f"} that is provided by the Smarty distribution.
  • Secondly - if $security is enabled, all php-functions that are to be used as modifiers have to be declared trusted in the MODIFIER_FUNCS element of the $security_settings array.

[bold added]

This is actually difficult to find in the documentation by searching, which (as of this writing) turns up zero results for "php" or "substr".

like image 167
czLukasss Avatar answered Nov 15 '22 06:11

czLukasss


You should use truncate modifier:

{$var|truncate:30}

More information here.

like image 25
Jojo Avatar answered Nov 15 '22 07:11

Jojo