Smarty模板引擎 學習記錄

 
 
 
 
   
  require_once('../smarty/Smarty.class.php');
  $smarty=new Smarty();
  //smarty口訣:五配置兩方法
  //五配置的介紹
  $smarty->left_delimiter="{";//左定界符
  $smarty->right_delimiter="}";//右定界符
  $smarty->template_dir="tpl"; //html 模板的地址
  $smarty->compile_dir="template_c"; //模板編譯生成的文件
  $smarty->cache_dir="cache"; //緩存
  //下面是開啓緩存的兩個配置
  $smarty->caching=true; //開啓緩存
  $smarty->cache_lifetime=120; //緩存時間
 
方法使用:
1.
void assign (string varname, mixed var)
用來賦值到模板中。能夠指定一對 名稱/數值 ,也能夠指定包含 名稱/數值 的聯合數組。
 
// passing name/value pairs 名稱/數值 方式
$smarty->assign("Name","Fred");
$smarty->assign("Address",$address);

// passing an associative array 聯合數組方式
$smarty->assign(array("city" => "Lincoln","state" => "Nebraska"));
 
2.
void display (string template [, string cache_id [, string compile_id]])
顯示模板,須要指定一個合法的 模板資源的類型和路徑。你還能夠經過 第二個可選參數指定一個緩存號。 經過第三個可選參數,能夠指定一個編譯號。這在你想把一個模板編譯成不一樣版本時使用,好比針對不一樣的語言編譯模板。編譯號的另一個做用是,若是你 有多個$template_dir模板目錄,但只有一個$compile_dir編譯後存檔目錄,這時能夠爲每個$template_dir模板目錄指 定一個編譯號,以免相同的模板文件在編譯後會互相覆蓋。相對於在每一次調用display()的時候都指定編譯號,也能夠經過設置 $compile_id編譯號屬性來一次性設定。
display 例子 顯示
include("Smarty.class.php");
$smarty = new Smarty;
$smarty->caching = true;

// only do db calls if cache doesn't exist
// 只有在緩存不存在時才調用數據庫
if(!$smarty->is_cached("index.tpl"))
{

 // dummy up some data
 $address = "245 N 50th";
 $db_data = array(
        "City" => "Lincoln",
     "State" => "Nebraska",
   "Zip" = > "68502"
        );

 $smarty->assign("Name","Fred");
 $smarty->assign("Address",$address);
 $smarty->assign($db_data);

}

// display the output
// 顯示輸出
$smarty->display("index.tpl");
 
3.
tpl變量調節輸出:
①{$var|capitalize} //首字母大寫
②{$var|cat:'string'}//字符串鏈接符(:至關於.)
  {$var|cat:'string1':'string2'}// 要輸出多個字符串只需:'srting'便可
③{$time|date_format:"%H:%M:%S"}  //date_format(time,format) 而date(format,time)
④{$var|default:'content'}  //將$var的默認值指定爲content(無論var是否有值)
⑤{$var|escape:'url'}  //將var轉碼爲URL模式(後面''裏指定轉碼模式)
⑥{$url|lower} {$url|upper}  //前面的將變量所有變爲小寫,後面的所有爲大寫
⑦{$var|nl2br}  //由於HTML不能識別換行符,這條語句將變量字符串裏的換行符轉換爲<br/>
 
例子:
//test.php
$smarty->assign('score','91');
 
//test.tpl
{if $score gt 90}
    優秀
{elseif $score gt 60}
    合格
{else}
   不及格
{/if}
 
循環方式
//test.php
 
$articlelist=array(
                array("title"=>"第一篇文章","author"=>"小J","content"=>"第一篇文章內存"),
                array("title"=>"第二篇文章","author"=>"小L","content"=>"第二篇文章內存"),
                );
  $smarty->assign('articlelist',$articlelist);
  $smarty->display('test.tpl');
 
//test.tpl
循環方法一:
{section name=article loop=$articlelist}  
        {$articlelist[article].title}
        {$articlelist[article].author}
        {$articlelist[article].content}
<br/>
{/section}
section 屬性
name: (必選) section 循環的名稱只是標示循環惟一的名字沒有特別意義,前面沒有 $ 符號;
loop: (必選)是在 php 聲明中的變量名稱,用來標示是循環哪個數組(即要循環數組名)須要使用 $
start: (可選)循環執行的初始位置 . 若是該值爲負數,開始位置從數組的尾部算起 . 例如:若是數組中有 7 個元素,指定 start -2 ,那麼指向當前數組的索引爲 5. 非法值 ( 超過了循環數組的下限 ) 將被自動調整爲最接近的合法值 .
step: (可選)如其它語言的循環,是一個步長,若是爲負數,則倒序循環;
max: (可選)循環的最大下標,若是是 1 則只循環 1 次,若是爲 2 則循環 2 次;
show :(可選)默認爲 true 即顯示。若是設置了 {sectionelse} 。表示若是數組沒有內容的時候顯示這部分的內容;若是 show false 則顯示這部分。若是沒有設置 {sectionelse} 則不輸出該數組。
 
循環方法二:
{foreach $articlelist as $article}
        {$article.title}
        {$article.author}
        {$article.content}
<br/>
{/foreach}
 
Smarty的引用
①{include file='header.tpl'} //輸出header.tpl文件內容
②{include file='header.tpl' sitename='content'}  //content 代替header.tpl文件中的 {$stitename}
 
Smarty類和對象賦值
/*在test.php 中定義且實例化的類,傳給test.tpl後,它能夠作直接對類的方法等直接使用 */
//test.php
 
 class My_object{
     function meth1($pam){
           return $pam[0].'個'.$pam[1];
        }
   }
  $my_obj=new My_object();
  $smarty->assign('my_obj',$my_obj);
  $smarty->display('test.tpl');
 
//test.tpl
{$my_obj->meth1(array('你是','好人'))}   //網頁輸出:你是個好人
 
Smarty函數的使用
example 1:
 
//test.php
$smarty->assign('time',time());
$smarty->display('test.tpl');
 
 
/*對於函數使用,| 前的做爲date函數的第一個參數,:後的做爲第二個參數*/
//test.tpl
{"Y-m-d"|date:$time}  //output: 2016-03-10
 
example 2:
/*PHP函數 str_replace($str1, $str2, $str) 其中將字符串 str 中的 第一個參數 替換爲 第二個參數*/
//test.php
$smarty->assign('str','asdfgh');
  $smarty->display('test.tpl');
 
//test.tpl
{'f'|str_replace:'k':$str} //將 str 中的 f 替換爲 k
 
 
example 3:
//test.php
 function test($params){
     $p1=$params['p1'];
     $p2=$params['p2'];
     return '穿入的鍵值1的值爲:'.$p1.',穿入的鍵值2的值爲:'.$p2;
  }
 
//註冊函數插件類型爲function,定義插件函數名爲f_test,test爲回調函數名稱
  $smarty->registerPlugin('function','f_test','test');  
  $smarty->display('test.tpl');
 
//test.tpl
{f_test p1='hhhh' p2='kkkk'}  //將一個數組 Array ( [p1] => hhhh [p2] => kkkk )回調給test.php中中test函數的參數$params
 
//output
穿入的鍵值1的值爲:hhhh,穿入的鍵值2的值爲:kkkk
 
 
 
MVC:  C經過M獲取數據,C又經過V將獲取的數據輸出,其中M是業務邏輯層是最核心的部分,若是發現本身的C層代碼愈來愈多可能就沒有很好的分清與M的分工
 
example 1:     //function 函數插件
//function.test.php
function smarty_function_test($params){    //smarty_function_插件名(至關於C)
      $width=$params['width'];
      $height=$params['height'];
      $area=$width*$height;
      return $area;
  }
 
//test.php
 $smarty->display('area.tpl');    // output:20000 (至關於V)
 
//area.tpl
{test width=100 height=200}  // $params獲取area.tpl回調的數組(至關於M)
 
example 2:     //modifiers 變量調節器插件
//modifier.test.php
 
function smarty_modifier_test($utime,$format){  
      return date($format,$utime);    //PHP的date(格式,時間戳)
 }
 
//test.php
 
 $smarty->assign('time',time());  //獲取本地時間戳
  $smarty->display('utime.tpl');   //輸出
 
//utime.tpl
{$time|test:'Y-m-d H:i:s'}  //$time做爲第一個變量傳參給$utime, 'Y-m-d H:i:s'傳參給$format(區別:function傳回的是數組)
 
 
example 3:     // block functions區塊函數插件(既能夠像function傳遞數組又能夠像modifier傳遞參數)且有閉標誌
 
//上面的提示說明,block再定義test函數會與function定義的test函數衝突,因此下面定義test1
 
//block.test1.php
function smarty_block_test1($params,$content){  //
    $replace=$params['replace'];
    $maxnum=$params['maxnum'];
    if($replace=='true'){
        $content=str_replace(',',',',$content);
        $content=str_replace('.','。',$content);
    }
    $str=substr($content,0,$maxnum);
    return $str;
  }
 
//test.php
$smarty->assign('str','Hello world,hello man and women,hell dog and pig.');
$smarty->display('block.tpl');
 
//block.tpl
{test1 replace='true' maxnum=200}   //將數組傳給$params
{$str}         //$str 將值傳參給 $content 
{/test1}     //注意:這裏有閉標誌
 
example 4:     //ORG第三方類庫的自定義
 
//function.php
 
 function C($name,$method){                   //實例化控制器函數
    require_once('/libs/Contorller/'.$name.'Controller.class.php');
    $controller=$name.'Controller';
    $obj=new $controller();
    $obj->$method();
  }
 
//自定義第三方類庫
function ORG($path,$name,$params=array()){
//path是路徑,name是第三方類名
//params是該類初始化時須要指定和賦值的類的屬性,格式爲array(屬性名=》屬性值.....) 
 
     require_once('libs/ORG/'.$path.$name.'.class.php');   //ORG是第三方插件類庫
     $obj=new $name();
     if(!empty($params)){
         foreach($params as $key=>$value){
             $obj->$key=$value;       //實例化對象屬性值
         }
     }
    return $obj;
  }
 
//config.php
//把smarty的配置專門放到配置文件中
$viewconfig=array('left_delimiter'=>'{','right_delimiter'=>'}','template_dir'=>'tpl','compile_dir'=>'template_c');  
 
 
  //index.php
  require_once('function.php');
  require_once('config.php');
  $view=ORG('Smarty/','Smarty',$viewconfig);   //把smarty的第三方類庫和smarty類以及smarty配置變量都傳遞給ORG函數
  $controller=$_GET['controller'];
  $method=$_GET['method'];
  C($controller,$method);
 
//testController.class.php
 
class testController{
      function show(){
        global $view;
        $view->assign('str','哈哈哈哈');
        $view->display('test.tpl');
      }
  }
 
//test.tpl
{$str}
 
//output:哈哈哈哈
相關文章
相關標籤/搜索