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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs