FORSMILE
JA
Smarty2016/02/16

[Smarty] Defining Variables and Arrays (assign)

Due to the nature of Smarty, it's generally recommended to handle these operations on the PHP side, but in practice, that's not always feasible.

Back to Blog

Due to the nature of Smarty, it's generally recommended to handle these operations on the PHP side, but in practice, that's not always feasible.

In reality, it's often necessary to create variables directly within the template.

DEFINING VARIABLES IN SMARTY

javascript
{assign var="name" value="山田"}
{assign "name" "山田"}

Simply creating a variable named 'name' is done as shown above. The second example is a shorthand.

javascript
{assign var="name" value=$user.name}
javascript
{assign var="total" value=$destroybonus+$score}

CONCATENATING STRINGS AND VARIABLES, OR VARIABLES AND VARIABLES

This feature is surprisingly useful. You can combine strings and variables to create new variables.

It's handy when you want to create multiple variables, for example, within a `foreach` loop.

javascript
{assign var='bonusImage' value="label`$bonusId`.png"}
javascript
{assign var="nextButton" value="`$color``$length`"}

COUNTING

javascript
{assign var="count" value=0}
{$count=$count+1}

$count++ does not cause an error but doesn't perform the calculation. Use this method when you need to increment in a `foreach` loop or similar.

REFERENCE: DEFINING ARRAYS

⇒ Reference: http://d.hatena.ne.jp/studio-m/20070512/1178978926

javascript
{assign_array var="fruits" values="apple,banana,orange"}

Smarty 3 seems to no longer require a plugin for this. Thank you for the information.

Recommended Smarty Books

While there are only older Smarty books available, mostly in Kindle format, the following is recommended for beginners.

📦
Amazon で関連書籍・ツールを検索
PHP template engine development
Amazonで探す →(アソシエイトリンク)