本文實例分析了Smarty模板常見的簡單應用。分享給大家供大家參考,具體如下:
首先要將smarty這個類包含進來:
include_once '../libs/Smarty.class.php';
然后創一個Smarty對象:
$smarty = new Smarty;
可以自定義Smarty 的開始結束符,默認為{ }
$smarty->left_delimiter ='<<'; //左符號為 <<$smarty->right_delimiter='>>'; //右符號 為 >>
最重要方法的好像是assign,如:
$smarty->assign('test',$te);//將$test的值付給test,在模板頁tpl中顯示用{$test}又如$arr=array(1,2,3);賦值仍是這樣:
$smarty->assign('arr',$arr);但在模板頁顯示時要借助foreach 或 section,foreach 用法如下:
{foreach item=item from=$arr key=ke name=foe} $item{/foreach}//此處的$item相當于$arr[$ke],foreach序列化{$smarty.foreach.foe.iteration}而section 用法如下:
{section name='test' loop=$arr}{$smarty.section.name.iteration}//使輸出序列化,序號從1開始,index從0開始{$arr[test]}{/section}最后最重要的一步操作千萬不要忘記那就是:
$smarty->display('test.tpl');下面說一些常用東西怎么樣的在模板上顯示
1.連接操作:
我叫{$str1|cat:"李白"};//輸出結果就是:我叫 $str1 李白2.當前日期:
{$str2|rdate_format:"Y%-m%-d%"} //輸出結果格式化$str2日期,形如0000-00-003.縮進:
{$str3|indent:8:"*"} //$str3前縮進8個* 默認縮進的是空格4.大小寫:
{$str4|lower} //$str4的小寫形式{$str4|upper} //$str4的大寫形式過濾:
{$url|escape:"url"} //對$url相關特殊字符進行替換<tr bgcolor='{cycle values="#EBEBEB,#ACABAB"}'>//tr背景交替 顏色分別為#EBEBEB,#ACABAB匹配替換:
{$str|regex_replace:"~[0-9]~":"asd"} //如果$str匹配[0-9]輸出asd替換
{$str|replace:"net":"com"} //將$str中的net全部替換成com包含頭模板文件:
{include file="top.tpl"}調用time.inc.php里面的函數:
{insert name="getCurrentTime" assign="current_time" script="time.inc.php"} 當前時間為{$current_time};{/insert}其中time.inc.php內容如下:
<?php function smarty_insert_getCurrentTime { return gmdate('l,j F Y g:i a T');//獲得當前日期及時間 }?>聯系:
mailto{mailto address="contact@smartyllc.com" subject="Smarty LLC Contact" encode="javascript"}載入test.conf:
{conf_load file="test.conf" section="test"}{#tt#}test.conf內容如下:
[test]tt = 12122
希望本文所述對大家基于smarty模板的PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選