1. 程式人生 > >smarty模板引擎工作原理

smarty模板引擎工作原理

1、模板引擎是什麼

展示給使用者的頁面由資料及承載資料的標籤組成,標籤就是html,而資料就是由php處理的變數,這樣就涉及到了前端和後端的互動,模板引擎就是將php程式碼與html程式碼分離的技術。
smarty是最常用的php模板引擎,由zend公司使用php編寫的一套模板引擎。

2、模板引擎的工作原理

模板引擎的工作原理就是php程式碼可以巢狀html標籤。
在不使用模板引擎的時候,我們可以通過這樣的程式碼來渲染頁面:

<?php 
$a = 1;
 ?>
 <?php if($a == 1){ ?>
 <h1><?php echo $a; ?></h1>
 <?php } ?>

而在smarty模板引擎下,則是將檔案分離成4部分:

  • php檔案:生產資料
  • 模板檔案:組織樣式
  • 編譯檔案:對html文件中的smarty標籤進行替換後的檔案
  • 快取檔案:對編譯檔案進行執行的結果再儲存為一個純html文件

上面的程式碼通過smarty來完成,在不開啟快取的情況下,需要建立兩個檔案,生成一個編譯檔案:

  • php檔案:
<?php
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$a = 1;
$smarty->_assign('a',$a);
$smarty->display('test.html')
 ?>
  • html檔案
<h1><{if $a eq 1}><{$a}><{/if}></h1>
  • 編譯檔案
<h1>?php if($a == 1){ ?><?php echo $a; ?><?php } ?></h1>

3、smarty中常用的方法

  • setTemplateDir()
    用於設定模板目錄,在載入模板目錄時,smarty會先在設定的模板目錄中找模板檔案,如果沒有設定,則在當前目錄下查詢
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setTemplateDir('template');
  • setCompileDir()
    用於設定編譯目錄,
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setCompileDir('compile');
  • setCacheDir()
    用於設定快取目錄
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setCompileDir('template_c');
  • setLeftDelimiter()/setRightDelimiter()
    用於設定左/右邊界符
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setLeftDelimiter('<{');
$smarty->setRightDelimiter('}>');

4、smarty中的快取

快取是一個讓程式設計師又愛又恨的東西。它既可以優化專案的效能,改善使用者體驗,但有時也會引發一些錯誤,甚至於在除錯過程中讓程式設計師花費太多時間在錯誤的方向上。因此我們更需要清晰地認識快取。

  • 開啟快取
    smarty預設是沒有開啟快取的,需要手動開啟。
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setCacheDir('cache');
$smarty->caching = true;
  • 設定快取時效
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setCacheLifetime(60);//單位:秒
  • 區域性快取
    smarty預設是針對模板進行整體快取,但有時我們需要的是僅快取公有、不變的部分,這時就需要用到區域性快取了
<{nocache}>
	……
<{/nocache}>

被nocache標籤包裹的部分,不會被smarty快取

  • 變數快取
    用於將指定變數傳遞到模板中,當nocached為true時,表示不快取
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->_assign(name,value【,nocached = false】);
  • 單頁面多快取
    單頁面是指一個html模板檔案,多快取生成多個快取檔案。
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->_display(tpl【,cacheid】);

cacheid為對模板檔案所產生的快取檔案的唯一標識

  • 判斷快取
    用於判斷指定的模板檔案是否以給定的cacheid生成快取檔案。在呼叫此方法前必須開啟快取,才能進行判斷
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->isCached(tpl【,cacheid】);
  • 刪除快取
    刪除指定的模板的快取檔案,如果指定cacheid,則只刪除給定的快取id的那個快取檔案。
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->clearCache(tpl【,cacheid】);