本篇文章為大家展示了如何正確的使用smarty模板,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
首先, 在官網下載smarty3模板文件,然后解壓。
在解壓之后的文件夾中,libs是smarty模板的核心文件,demo里面有示例程序。
我們把libs文件夾復制到我們的工作目錄,然后重命名為smarty。

假設我們在controller目錄下的index.php中使用smarty模板。
index.php
<?php
require '../smarty/Smarty.class.php';
$smarty = new Smarty;
$smarty->debugging = false; //開啟debug模式
$smarty->caching = true; //開啟緩存
$smarty->cache_lifetime = 120; //緩存時間
$smarty->left_delimiter = '<{'; //左定界符
$smarty->right_delimiter = '}>'; //右定界符
$smarty->template_dir = __DIR__.'/../view/'; //視圖目錄
$smarty->compile_dir = __DIR__ . '/../smarty/compile/'; //編譯目錄
$smarty->config_dir = __DIR__ . '/../smarty/configs/'; //配置目錄
$smarty->cache_dir = __DIR__ . '/../smarty/cache/'; //緩存目錄
$list = range('A', 'D');
$smarty->assign("list", $list);
$smarty->assign("name", "zhezhao");
$smarty->display('index.html');模板文件index.html
<html>
<head>
<title></title>
</head>
<body>
<p><h2><{$name}></h2></p>
<{foreach $list as $k=>$v }>
<p><h2><{$k}> : <{$v}></h2></p>
<{/foreach}>
</body>
</html>上述方法的優點是使用起來配置比較簡單,缺點也是顯而易見的,我們controller目錄下可能有很多頁面調用smarty模板,在每個頁面都需要將上述方法配置一遍。
解決方法有兩種:
將smarty模板的配置信息寫到一個文件中,然后其他頁面可以通過包含該文件使用smarty對象。
require '../smarty/Smarty.class.php';
$smarty = new Smarty;
$smarty->debugging = false; //開啟debug模式
$smarty->caching = true; //開啟緩存
$smarty->cache_lifetime = 120; //緩存時間
$smarty->left_delimiter = '<{'; //左定界符
$smarty->right_delimiter = '}>'; //右定界符
$smarty->template_dir = __DIR__.'/../view/'; //視圖目錄
$smarty->compile_dir = __DIR__ . '/../smarty/compile/'; //編譯目錄
$smarty->config_dir = __DIR__ . '/../smarty/configs/'; //配置目錄
$smarty->cache_dir = __DIR__ . '/../smarty/cache/'; //緩存目錄我們自己編寫一個類,繼承自Smarty類,然后將配置信息寫在構造函數中。
我們編寫mySmarty類
<?php
require '../smarty/Smarty.class.php';
class mySmarty extends Smarty{
public function __construct(array $options = array()){
parent::__construct($options);
$this->debugging = false; //開啟debug模式
$this->caching = true; //開啟緩存
$this->cache_lifetime = 120; //緩存時間
$this->left_delimiter = '<{'; //左定界符
$this->right_delimiter = '}>'; //右定界符
$this->setTemplateDir(__DIR__.'/../view/'); //視圖目錄
$this->setCompileDir(__DIR__ . '/../smarty/compile/'); //編譯目錄
$this->setConfigDir(__DIR__ . '/../smarty/configs/'); //配置目錄
$this->setCacheDir(__DIR__ . '/../smarty/cache/'); //緩存目錄
}
}此時,controller里面的index.php代碼可優化為:
<?php
require 'mySmarty.php';
$smarty = new mySmarty;
$list = range('A', 'D');
$smarty->assign("list", $list);
$smarty->assign("name", "zhezhao");
$smarty->display('index.html');上述內容就是如何正確的使用smarty模板,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。