DEV Community

dgloriaweb
dgloriaweb

Posted on • Edited on

1

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay