Smarty變量用法詳解

字號:


    本文實例講述了Smarty變量用法。分享給大家供大家參考,具體如下:
    1. 從PHP分配的變量
    調(diào)用從PHP分配的變量需在前加"$"符號.(譯注:同php一樣)
    調(diào)用模板內(nèi)的assign函數(shù)分配的變量也是這樣.(譯注:也是用$加變量名來調(diào)用)
    示例:
    index.php:
    $smarty = new Smarty;
    $smarty->assign('firstname', 'Doug');
    $smarty->assign('lastLoginDate', 'January11th, 2001');
    $smarty->display('index.tpl');
    index.tpl:
    Hello {$firstname}, glad to see you couldmake it.
    <p>
    Your last login was on {$lastLoginDate}.
    輸出:
    Hello Doug, glad to see you could make it.
    <p>
    Your last login was on January 11th, 2001.
    2. 從配置文件讀取的變量
    配置文件中的變量需要通過用兩個"#"或者是smarty的保留變量 $smarty.config.來調(diào)用(后面會講到)
    第二種語法在變量作為屬性值并被引號括住的時候非常有用.
    (譯注:舉個例子 {include file="#includefile#"} 這樣#includefile#將被當作字符處理,而不表示配置文件變量,但可以這樣表示{include file="`$smarty.config.includefile`"}不要忘了加``)
    示例:
    foo.conf:
    pageTitle = "This is mine"
    bodyBgColor = "#eeeeee"
    tableBorderSize = "3"
    tableBgColor = "#bbbbbb"
    rowBgColor = "#cccccc"
    index.tpl:
    {config_load file="foo.conf"}
    <html>
    <title>{#pageTitle#}</title>
    <body bgcolor="{#bodyBgColor#}">
    <table bgcolor="{#tableBgColor#}">
    <tr bgcolor="{#rowBgColor#}">
        <td>First</td>
        <td>Last</td>
        <td>Address</td>
    </tr>
    </table>
    </body>
    </html>
    index.tpl:
    {config_load file="foo.conf"}
    <html>
    <title>{$smarty.config.pageTitle}</title>
    <body bgcolor="{$smarty.config.bodyBgColor}">
    <tablebgcolor="{$smarty.config.tableBgColor}">
    <tr bgcolor="{$smarty.config.rowBgColor}">
        <td>First</td>
        <td>Last</td>
        <td>Address</td>
    </tr>
    </table>
    </body>
    </html>
    上述兩種模板寫法都輸出:
    <html>
    <title>This is mine</title>
    <body bgcolor="#eeeeee">
    <table bgcolor="#bbbbbb">
    <tr bgcolor="#cccccc">
        <td>First</td>
        <td>Last</td>
        <td>Address</td>
    </tr>
    </table>
    </body>
    </html>
    配置文件的變量只有在它們被加載以后才能使用.
    希望本文所述對大家基于smarty模板的PHP程序設計有所幫助。