$tpl=new Smarty();//新建一個(gè)smarty對(duì)象,我使用的是Smarty-3.1.6版本
1.設(shè)置smarty模板路徑$tpl->setTemplateDir();默認(rèn)情況下是templates
2.設(shè)置smarty模板編譯路徑$tpl->setCompileDir();默認(rèn)情況下是templates_c
3.設(shè)置smarty模板引擎的左右 分隔符,
       $tpl->left_delimiter="<{";
       $tpl->right_delimiter="}>";
       默認(rèn)情況下:public $left_delimiter = "{";//smarty源代碼
                        public $right_delimiter = "}";//smarty源代碼
    為什么我們要改這些分隔符?
  因?yàn)楸热缭谳^早版本smarty引擎模板中,會(huì)報(bào)錯(cuò),不能自動(dòng)識(shí)別。
比如: 
<style> 
div{margin:0;} 
</style> 
或者 javascript中 
復(fù)制代碼 代碼如下:
 
<script> 
function show(){ 
alert("smarty"); 
} 
</script> 
 
這兩種情況下,都有“左右大括號(hào)”,smarty引擎碰到會(huì)報(bào)錯(cuò) 
4.初始化操作我們可以在外部另外創(chuàng)建一個(gè)初始化操作的php文件,如:smarty.ini.php。然后在php文件中包括進(jìn)來即可 
復(fù)制代碼 代碼如下:
 
<?php 
include "../Smarty3.1.6/libs/Smarty.class.php"; 
$tpl=new Smarty(); 
$tpl->setTemplateDir("./Tpl"); 
$tpl->setTemplateDir("./Compile"); 
$tpl->left_delimiter="<{"; 
$tpl->right_delimiter="}>"; 
?> 
 
5.使用smarty模板引擎的display函數(shù)或者include其他模板時(shí),都得以smarty對(duì)象中指定的模板目錄(比如:Tpl目錄,默認(rèn)是templates目錄)為基目錄。 
  ①模板目錄是:Tpl,該目錄下存放著很多模板,有default,green,red模板,default模板目錄下有很多模板文件(index.tpl、header.tpl、footer.tpl),此時(shí)display的正確用法:$tpl->display(“default/index.tpl”);即基目錄下的default模板目錄 
  ②在模板文件(如:index.tpl)中包含其他模板文件時(shí)(如:header.tpl、footer.tpl),include的正確寫法應(yīng)該是:<{include “default/header.tpl”}> 、<{include “default/footer.tpl”}> 
  雖然index.tpl、header.tpl、footer.tpl都在同一個(gè)目錄下,但是<{include “header.tpl”}> 、<{include “footer.tpl”}>是錯(cuò)誤的寫法,這種情況,smarty引擎會(huì)到Tpl目錄下找header和footer,而不是在default下面查找 
6.如果要想讓各個(gè)目錄下的PHP程序都可以加載Smarty和使用Smarty指定的模板目錄和編譯目錄,唯一的辦法是使用絕對(duì)路徑。 
7.Smarty模板引擎中訪問變量的方式(模板中的變量前記得加”$”符號(hào)) 
①訪問數(shù)組 
索引數(shù)組: 
   $tpl->assign("arr",array("aa","bb","cc")); 
   $tpl->assign("arr2",array(array("二維數(shù)組一一","二維數(shù)組一二"),array("二維數(shù)組二一","二維數(shù)組二二"))); 
     訪問索引數(shù)組:<{ $arr[0] }>、<{ $arr[0] }>、<{ $arr[0] }> 
   訪問二維索引數(shù)組:<{ $arr2[0][0] }>、<{ $arr2[0][1] }> 
關(guān)聯(lián)數(shù)組:(使用 . 符號(hào)來訪問) 
   訪問關(guān)聯(lián)數(shù)組:<{$arr3.id}>、<{$arr3.name}>、<{$arr3.age}> 
②訪問對(duì)象 
創(chuàng)建對(duì)象:   
復(fù)制代碼 代碼如下:
  
class human{ 
private $sex; 
private $name; 
private $age; 
public function __construct($s,$n,$a){ 
$this->sex=$s; 
$this->name=$n; 
$this->age=$a; 
} 
public function print_info(){ 
return $this->sex."--".$this->name."--".$this->age; 
} 
} 
$tpl->assign("student",new human("male","MarcoFly",22)); 
 
給模板中的對(duì)象賦值:<{$student->print_info()}> 
8.Smarty模板引擎中的數(shù)學(xué)運(yùn)算可以應(yīng)用到模板變量中 
給變量賦值 
    $tpl->assign("num1",10); 
    $tpl->assign("num2",5.5); 
模板變量輸出 
    <{$num1}> //結(jié)果10 
    <{$num2}> //結(jié)果5.5 
    <{$num1+$num2}> //結(jié)果15.5 
    <{$num1+$num2*$num2/$num1}>//結(jié)果13.025 
原創(chuàng)文章 
轉(zhuǎn)載請(qǐng)注明:WEB開發(fā)_小飛