21

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

Zsolt Szilagyi
  • 4,741
  • 4
  • 28
  • 44
Rami Dabain
  • 4,709
  • 12
  • 62
  • 106

3 Answers3

31

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".

TheDudeAbides
  • 1,821
  • 1
  • 21
  • 29
czLukasss
  • 730
  • 8
  • 16
  • 1
    This definitely works, but it's not actually a Smarty function, it's a PHP function that you can access from within Smarty. – Russell G Oct 02 '15 at 14:21
  • Smarty 4.3 has deprecated using PHP functions as modifiers - https://github.com/smarty-php/smarty/issues/813 - you will now need to create/register your own custom modifier to wrap the PHP function if forward compatibility is important. Alternately use a smarty modifier such as |truncate. – Chris Wheeler Dec 21 '22 at 12:08
25

You should use truncate modifier:

{$var|truncate:30}

More information here.

Jojo
  • 1,875
  • 3
  • 29
  • 29
-2

Regarding to your problem Jojo already gave the correct answer.

You should use truncate modifier:

{$var|truncate:30}

But for usability and seo-reaons it would be better to shorten the text via css with text-overflow property. It allows you to print the whole text out to the client but shorten it to a specific width/length and show ... instead.

Community
  • 1
  • 1
Roman
  • 2,530
  • 2
  • 27
  • 50