This article mainly introduces the usage of built-in functions of smarty template engine. It analyzes the foreach function and if... The usage of built-in functions such as else..., if...elseif...elseif...else... and other built-in functions have certain reference value. Friends in need can refer to it
The example in this article describes how to use smarty’s built-in functions. Share it with everyone for your reference. The details are as follows:
In-build (built-in), in the smarty template, many built-in function libraries are provided. For specific usage, please refer to the chm version of the smarty Chinese manual.
1.foreach function
The operand array is as follows:
?
3 4 5 6 7
8
9
|
//Index array $res=array('Shanghai','Beijing','Shenzhen'); $smarty->assign("arr",$res); //Associative array $res2=array('city1'=>'Beijing','city2'=>'Guangzhou','city3'=>'Hunan'); $smarty->assign("arr2",$res2); //Index two-dimensional array $res3 = array( array('Xiaoxiao','Changshan','Wu Bei'), array('Shanshan','Changming') ); $smarty->assign("arr3",$res3); //Associated two-dimensional array $res4 = array( array('id'=>'001','name'=>'Zhang San','email'=>'zhangsan@1163.com'), array('url'=>'http://www.baidu.com','age'=>'28') ); $smarty->assign("arr4",$res4); //Associated two-dimensional array 2 $res5=array( 'emp1'=>array('id'=>'001','name'=>'Zhang San','email'=>'zhangsan@1163.com'), 'emp2'=>array('url'=>'http://www.baidu.com','age'=>'28') ); $smarty->assign("arr5",$res5); |
1 2 3 4 5 6 7 8 9 |
<{foreach from=$arr item=temp}> <{$temp}> Associative array: <{foreach from=$arr2 item=temp key=k}> <{$k}>=<{$temp}> |
Note: from, item, key are fixed
Two-dimensional array
?
3 4
5
6
9 10
11 12
|
Two-dimensional index array: <{foreach from=$arr3 item=temp key=k}> <{*temp here is an array*}> <{foreach from=$temp item=val}> <{$val}> <{/foreach}> <{/foreach}> Two-dimensional associative array format 1: <{foreach from=$arr4 item=temp}> <{*The outer key is not needed, so no key is added*}> <{foreach from=$temp item=val key=k}> <{*The inner key is required, add key*}> <{$k}>=<{$val}> <{/foreach}> <{/foreach}> Two-dimensional associative array format 2: <{foreach from=$arr5 item=temp key=k}> <{$k}>: <{foreach from=$temp item=val key=k2}> <{$k2}>=<{$val }> <{/foreach}> <{/foreach}> |
1 2 3 4 5 | <{if $age>10 }> Age greater than 10, age: <{$age}> <{else}> If you are less than 10 years old, your age is: <{$age}> <{/if}> |
1 2 3 4 5 6 | $res4 = array( array('id'=>'001','age'=>'4'), array('id'=>'002','age'=>'16'), array('id'=>'003','age'=>'20'), array('id'=>'004','age'=>'80') ); |
The template is quoted as follows:
?
3 4 5
|
<{foreach from=$arr4 item=temp }>
<{if $temp.age < 5}> |