Smarty Functions

Smarty offers many built-in functions, but a handful cover almost everything you'll need in a theme. This page introduces those.

Note: in Smarty syntax, where you do and don't use the $ prefix matters — get it wrong and the template won't behave the way you expect.

IF

Smarty's if statement:

{if <condition>}
    <contents that will be used if the condition is satisfied>
{else}
    <contents that will be used if the condition is not satisfied>
{/if}

The <condition> is similar to PHP syntax. A couple of examples:

  • {if $my_variable} — true if $my_variable is not empty
  • {if $my_variable==5} — true if $my_variable equals 5

Some variables a module provides are optional and aren't always passed. In that case, check whether the variable is set and adjust what you display accordingly.

FOREACH

To loop over an array instead of a single variable, use foreach:

{foreach key=key_name item=item_name from=$variable_you_are_parsing}
    ...
{/foreach}

Inside the loop you get two variables: $key_name and $item_name (rename them however you like). $key_name holds the key the current value was stored under — often just a number, sometimes something more meaningful — while $item_name holds the value itself.

ASSIGN

You'll rarely need this one. It's useful when you need to, say, track a counter to decide where to place a line break.

{assign var=variable_name value=<new_value>}

To increment a variable by one:

{assign var=x value=$x+1}