smarty模板引擎之內(nèi)建函數(shù)用法

字號(hào):


    這篇文章主要介紹了smarty模板引擎之內(nèi)建函數(shù)用法,實(shí)例分析了smarty中foreach函數(shù)、if...else...、if...elseif...elseif...else...等內(nèi)建函數(shù)的使用方法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    本文實(shí)例講述了smarty內(nèi)建函數(shù)的使用方法。分享給大家供大家參考。具體如下:
    in-build(內(nèi)建),在smarty模板中,提供了很多內(nèi)建的函數(shù)庫(kù),具體使用可以參考smarty中文手冊(cè)chm版本。
    1.foreach函數(shù)
    操作數(shù)組如下:
    //索引數(shù)組
    $res=array('上海','北京','深圳');
    $smarty->assign("arr",$res);
    //關(guān)聯(lián)數(shù)組
    $res2=array('city1'=>'北京','city2'=>'廣州','city3'=>'湖南');
    $smarty->assign("arr2",$res2);
    //索引二維數(shù)組
    $res3 = array(
    array('瀟曉','常山','吳蓓'),array('珊珊','常明')
    );
    $smarty->assign("arr3",$res3);
    //關(guān)聯(lián)二維數(shù)組
    $res4 = array(
    array('id'=>'001','name'=>'張三','email'=>'zhangsan@1163.com'),
    array('url'=>'http://www.baidu.com','age'=>'28')
    );
    $smarty->assign("arr4",$res4);
    //關(guān)聯(lián)二維數(shù)組2
    $res5=array(
    'emp1'=>array('id'=>'001','name'=>'張三','email'=>'zhangsan@1163.com'),
    'emp2'=>array('url'=>'http://www.baidu.com','age'=>'28')
    );
    $smarty->assign("arr5",$res5);
    遍歷數(shù)組:
    其中from、item、key是固定寫(xiě)法,key可以根據(jù)需求加
    一維數(shù)組
    索引數(shù)組:
    <br/>
    <{foreach from=$arr item=temp}>
    <{$temp}> <t/>
    <{/foreach}>
    <br/>關(guān)聯(lián)數(shù)組:<br/>
    <{foreach from=$arr2 item=temp key=k}>
    <{$k}>=<{$temp}><t/>
    <{/foreach}>
    <br/>
    備注:from、item、key是固定的
    二維數(shù)組
    <br/>二維索引數(shù)組:<br/>
    <{foreach from=$arr3 item=temp key=k}>
    <{*這里的temp是一個(gè)數(shù)組*}>
    <{foreach from=$temp item=val}>
    <{$val}>
    <{/foreach}>
    <{/foreach}>
    <br/>二維關(guān)聯(lián)數(shù)組格式1:<br/>
    <{foreach from=$arr4 item=temp}>
    <{*外層的鍵不需要,所以不添加key*}>
    <{foreach from=$temp item=val key=k}>
    <{*內(nèi)層的鍵需要,添加key*}>
    <{$k}>=<{$val}>
    <{/foreach}>
    <{/foreach}>
    <br/>二維關(guān)聯(lián)數(shù)組格式2:<br/>
    <{foreach from=$arr5 item=temp key=k}>
    <{$k}>:
    <{foreach from=$temp item=val key=k2}>
    <{$k2}>=<{$val }>
    <{/foreach}>
    <br/>
    <{/foreach}>
    2.if...else...
    <{if $age>10 }>
    年齡大于10,年齡為:<{$age}>
    <{else}>
    年齡小于10,年齡為:<{$age}>
    <{/if}>
    3.if...elseif...elseif...else...
    已知數(shù)據(jù)源如下:
    $res4 = array(
    array('id'=>'001','age'=>'4'),
    array('id'=>'002','age'=>'16'),
    array('id'=>'003','age'=>'20'),
    array('id'=>'004','age'=>'80')
    );
    模板中引用如下:
    <{foreach from=$arr4 item=temp }>
    <{if $temp.age < 5}>
    <{$temp.id}>,你是小孩
    <{elseif $temp.age >=5 and $temp.age <= 18}>
    <{$temp.id}>,你是年輕人
    <{elseif $temp.age > 18 and $temp.age <= 50}>
    <{$temp.id}>,你是成年人
    <{else}>
    <{$temp.id}>,年齡<span>比較大了</span>
    <{/if}>
    <{/foreach}
    希望本文所述對(duì)大家的php程序設(shè)計(jì)有所幫助。