DEV Community

dgloriaweb
dgloriaweb

Posted on • Edited on

Php Smarty template - assigning complex content to variables

In some cases Smarty doesn't allow you to assign values to variables just like that. For example in foreach loops. Then the following solutions can work.
1, Assign a simple text with variables:

{assign "myVar2" "myVar1 content=$myVar1"}
Enter fullscreen mode Exit fullscreen mode

explanation: Smarty's smart enough to replace value of variable within quotes.

2, Assign special characters or longer text:

{capture assign="myVar3"}mytext{$myVar1}_{$myVar2}{/capture}
Enter fullscreen mode Exit fullscreen mode

explanation: the capture tag allows you to add text without quotes so it's readable. Variables have to be in {}.

3, Do ternary operation and assign value:

{$myVar4= ($myVar1|strstr:"my sample text")?1:0}
Enter fullscreen mode Exit fullscreen mode

explanation: need to be aware of the brackets, but works fine. Normal brackets contain the condition.

Ternary operator concatenate variables with string (if the parentname is set, concatenate variables to a new string)

{$prodName = ($parentname) ? "`$parentname` - `$name`" : $name}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)