最近投靠了一家新公司,前后端不分離,某端的頁面寫法有用到smarty,簡單了解下smarty語法
1.smarty的配置
首先,使用smarty第一件事是先配置好墨吓,一般有以下9行代碼
require_once("smarty/libs/Smarty_class.php"); //把smarty的類定義文件包含進來
$smarty=new smarty();
$smarty->config_dir="smarty/libs/Config_File.class.php";
$smarty->caching=false; //是否使用緩存球匕,項目在調(diào)試期間,不建議啟用緩存
$smarty->cache_dir="smarty_cache/"; //緩存文件夾
$smarty->template_dir="smarty_tpl"; //模板文件夾
$smarty->compile_dir="smarty_compile"; //編譯文件夾
$smarty->left_delimiter="<{"; // 標簽符定義不是必要的帖烘,smarty默認是使用"<"和">"亮曹,強烈建議更換。
//因為如果smarty的標簽剛好在javascript語句里面時秘症,沖突的可能性很大
$smarty->right_delimiter="}>";
以上的9行代碼可以放在一個獨立的文件照卦,需要使用smarty的頁面引用進來即可
- smarty的使用
smarty替換標簽的語法:
smarty->assign("標簽名","值");
smarty->display("index.html"); //顯示內(nèi)容,index為模板文件名
假定模板文件里面有一個標簽 <{ $user_name }> (注意:標簽里面的變量必須帶$)
那么在PHP文件可以:
$new_name="Joan";
smarty->assign("user_name",$new_name); (注意:在此時,user_name是不帶$的)
smarty->display("index.html"); //顯示內(nèi)容,index為模板文件名
- smarty的循環(huán)
循環(huán)的使用在php文件像處理普通標簽一樣處理
模板文件代碼:
<{section name=s loop=$stu}>
<{/section}>
<{$stu[s]}>
那么在PHP文件可以:
假如有一個數(shù)組乡摹,或一個記錄集 $rs
$smarty->assign("stu",$rs);
$smarty->display("index.html"); //在PHP文件處理循環(huán)標簽和普通標簽沒什么區(qū)別役耕。
- smarty的if 語法
模板文件
<{if $my_r>500 }>
<{$my_r}>
<{/if}>
php文件:
$aa=123;
$smarty->assign("my_r",$aa);
$smarty->display("in.html");
上例中,如果$aa>500聪廉,my_r的標簽就能顯示出來瞬痘,否則不顯示故慈。
<{ if 條件 }> //此處的條件不要加括號,也不要像basic語言那樣在后面加 then
<{/if}>
- smarty循環(huán)配合if 使用實例
PHP文件
----------------------------------
$aa[0]=123;
$aa[1]=456;
$aa[2]=789;
$smarty->assign("my_r",$aa);
$smarty->display("in.html");
模板文件
<{ section name=s loop=$my_r }>
<{if $my_r[s]>200 }>
<{$my_r[s]}>
<{else}>
小于200
<{/if}>
<{/section}>
上例中框全,只顯示大于200的數(shù)值