smarty3.1.30 模板引擎的使用
模板引擎簡介
模板引擎就是將用戶界面(html)和程序代碼(php)分離的一種解決方案。
eg:
沒有使用第三方庫,使用PHP內置函數,只是簡單的字符串處理。
tmp.html文件
index.php文件
<?php$str = file_get_contents("./tmp.html");$str = str_replace('{welcome}',"歡迎",$str);$str = str_replace('{hang}',"你",$str);echo $str;smarty特點
smarty下載與文件介紹
下載smarty
文件解壓后:
demo:系統(tǒng)提供的實例文件
libs:核心文件
– plugins:自定義插件文件夾
– sysplugins:系統(tǒng)插件文件夾
– debug.tpl:調試模板
– Smarty.class.php:Smarty3.0中的核心類文件
– SmartyBC.class.php:向后兼容類,Smarty2.0版本
smarty使用
創(chuàng)建文件目錄,目錄樹在后圖有
templates:定義默認模板文件夾
templates_c:定義編譯目錄
cache:定義緩存文件夾
configs:定義默認配置文件夾
緩存
$smarty->caching = true; // 開啟緩存
$smarty->cache_lifetime = 120; // 緩存文件時間
調試
$smarty->debugging = true; // 開啟調試
初步使用舉例 eg,只添加了兩個文件:
index.php
index.tpl
<html><head><title>Smarty 初步</title><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></head><body><div style="color:red;font-size:20px;">{$title}</div><br><hr><br><p>{$hang}</p></body> </html>文件結構
恭喜,已入門,是時候表演真正的技術了
smarty 重要的就是Smarty.class.php文件,建議閱讀一遍,查看相關屬性方法
smarty 相關屬性和方法
2.1 $smarty->assign("title","welcome"); // 傳welcome 到模板中 替換title
2.2 $smarty->display("index.tpl"); // 顯示并輸出相應的模板,目錄是默認模板配置目錄
2.3
3.1 $smarty->setTemplateDir("./templates"); // 修改默認模板文件夾
3.1 $smarty->setCompileDir("./templates_c"); // 修改默認編譯文件夾
3.1 $smarty->setConfigDir("./configs"); // 修改默認配置文件夾
3.1 $smarty->setCacheDir("./cache"); // 修改默認緩存文件夾
$smarty->debugging = true; // 開啟調試
編程中的現實問題
注釋代碼
{* 這里是smarty注釋 *} <br> <!-- 這里是HTML注釋 --> <p>{$hang}</p>復雜變量(數組、多維數組、對象)的使用
// smarty文件 $smarty->assign("array_yi", array("jh","hn","dy")); $smarty->assign("array_er", array(array(0,1),array("00","11"),array("000","111"))); $smarty->assign("contacts", array(array("phone"=>"phph"),array("phone" => "555"))); class Person {private $name;function __construct($name){$this->name = $name;}public function speak(){echo $this->name.'在說話...';} } $smarty->assign('user',new Person("jh"));// 模板文件 <p>{$array_yi[2]}</p> <p>{$array_er[2][1]}</p> <p>{$contacts[1]["phone"]}</p> <p>{$user->speak()}</p>// 結果 dy 111 555 jh在說話...模板文件中自建臨時變量
{assign var='temp' value='聲明一個temp變量并賦值'} {$temp} {$temp = "另一種方法"} {$temp} {$temp = array("jh","聲明數組")} {$temp[1]}// 結果 聲明一個temp變量并賦值 另一種方法 聲明數組從配置文件中讀取變量 - 配置文件在config目錄下
// 配置文件 name = Welcome to Smarty! // 全局變量[jubu] jubu_name = jubu_var // 局部變量// 模板文件使用配置文件變量 {config_load file = "config.txt"} // 全局變量使用 {$smarty.config.name}{config_load file = "config.txt" section="jubu"} // 局部變量使用 {$smarty.config.name} {$smarty.config.jubu_name}模板使用PHP文件的函數 - 自定義函數
// index.php function hehe() {return "hehehehe"; }// 模板文件 {hehe()}smarty預保留變量 - 超全局變量
{$smarty.template} {* 模板的名稱 *} {$smarty.get.page} {* 相當于 $_GET['page'] *} {$smarty.post.page} {* 相當于 $_POST['page'] *} {$smarty.config} {* 讀取配置文件里變量,后面加變量名。等效{#變量名#} *} {$smarty.cookies.username} {* 相當于 $_COOKIES['username'] *} {$smarty.server.SERVER_NAME} {* 相當于 $_SERVER['SERVER_NAME'] *} {$smarty.env.Path} {* 相當于 $_ENV['Path'] *} {$smarty.session.id} {* 相當于 $_SESSION['id'] *} {$smarty.request.username} {* 相當于 $_REQUEST['username'] *} {$smarty.now} {* 獲取當前時間戳 *} {$smarty.current_dir} {* 獲取當前模板目錄 *} {$smarty.version} {* 獲取當前Smarty版本 *} {$smarty.now|date_format:'%Y-%m-%d %H:%M:%S'}變量調節(jié)器(文本格式化)
{$var|capitalize} {* 首字母大寫 *} {$var|count_characters:true} {* 字符計數 *} {$var|cat:var2} {* 連接字符串 *} {$var|count_paragraphs} {* 段落計數 *} {$var|count_sentences} {* 句子計數 *} {$var|count_words} {* 計算詞數 *} {$var|data_format:"%Y%m%d"} {* 時間格式化 *} {$var|default:"value"} {* 如果變量為空或為定義,那么采用默認值 *} {$var|escape} {* 編譯轉碼 *} {$var|indent:10:"*"} {* 首行縮進,后面的參數表示每個縮進字符要放的字符 *} {$var|lower} {* 字符串小寫 *} {$var|nl2br} {* \n轉<br/> *} {$var|regex_replace:"/[\t\n]/",""} {* 正則替換 *} {$var|spacify:"^^"} {* 在字符之間插入相應字符如^^ *} {$var|string_format:'%d'} {* 字符串格式化 *} {$var|strip:'*'} {* 去掉重復空格 *} {$var|strip_tags} {* 去除html標簽 *} {$var|truncate:30:'...'} {* 字符串截取,注意,優(yōu)缺點 *} {$var|upper} {* 大寫 *} {$var|wordwrap:30:'<br>'} {* 行寬約 *}// 可以自建調節(jié)器 // 組合調節(jié)器 {$var|lower|truncate:30|spacify}smarty 模板內置函數
{debug} 開啟調試窗口
捕獲一段HTML代碼
{capture name="content"} <h1>h1</h1><br> <center>center</center> {/capture}{$smarty.capture.content}foreach - PHP方式
{foreach $array_yi as $key => $val}{$key} {$val} {/foreach}foreach - smarty語法進行遍歷
{foreach from=$array_yi key="key" name="array_yi" item="val"}{$key} {$val} {/foreach}二維數組循環(huán)遍歷 - 方式一
{foreach $array_er as $val}{$val[1]} {/foreach}二維數組循環(huán)遍歷 - 方式二
{foreach from=$array_er key="key" name="array_er" item="val"}{$val@iteration}{$val[0]} {/foreach} 共循環(huán)了{$smarty.foreach.array_er.total}次 | {$val@total}次// 內置其他函數 {$smarty.foreach.name.index} {* @index 下標0 *} {$smarty.foreach.name.iteration} {* @iteration 迭代(當前是第幾次循環(huán)),默認從1開始 *} {$smarty.foreach.name.first} {* @first bool當時第一次該值為真 *} {$smarty.foreach.name.last} {* @last bool當時最后一次該值為真 *} {$smarty.foreach.name.show} {* @show 數據顯示true顯示數據,false不顯示數據 *} {$smarty.foreach.name.total} {* @total 循環(huán)的總次數 *}二維數組循環(huán)遍歷 - 方式三
// name:代表section名稱,在循環(huán)過程中,會作為索引,必選 // loop:代表循環(huán)數組,由其來確定循環(huán)的次數,必選 // start:默認從第幾個元素開始遍歷 // step:每次循環(huán)次數,默認是1 // max:最大循環(huán)次數{section name=索引 loop=循環(huán)數組 start=開始(0) step=步階(1) max=最大循環(huán)次數} {/section}// 舉例 {section name="index" loop=$array_er}{$array_er[index][0]}{$array_er[index][1]} {/section}fetch 載入文件/引入文件到當前文件,并賦值給變量
{fetch file="./configs/other.config" assign="ddd"} {$ddd} // 結果 => 輸出改文件所有信息include 模板
{include file='other.html'}include_php 文件
{include_php file='other.php'}if elseif else
{if empty($title)} have title {elseif $title} title is {$title} {else} no title {/if}literal 字符原樣輸出,不解析
{literal}{$title} {/literal}// 結果 {$title}strip 字符原樣輸出,不解析
{strip}.... {/strip}// 功能及應用:去除任何位于{strip}{/strip}標記數據中記錄的首尾空格和回車,// 可以保證模板容易理解且不用擔心多余的空格導致問題counter - 進行計數
cycle 實現輪顯效果
{html_image file=”pumplink.png”} 引用一張圖片
{html_table loop=$data cols=4 table_attr=”border=0”} 循環(huán)輸出數組到一張表
html_checkboxes 、 html_options 、 html_radios 作為拓展需要使用去查詢
編寫PHP程序(非模板程序)上面要注意的哪些 和 輔助開發(fā)函數、變量
SMARTY_DIR 常量 = Smarty.class.php文件的路徑
assign 分配變量到模板文件
assignByRef 分配變量到模板文件(引用)
append 追加數據到數組,過程分為兩步
第一是追加數據到數組中
第二分配變量到模板文件中(也就不需要assign賦值了)
appendByRef 追加元素地址到數組中
clearAllAssign 清除所有賦值變量
clearAssign 清除指定變量的值
clearCache 清理緩存
configLoad 載入配置文件
clearConfig 清除配置文件信息
display 執(zhí)行輸出并顯示指定頁面
fetch 載入文件到字符串 - 不同于模板中的fetch函數
過濾器
如果頁面有臨時緩存,謹慎使用過濾器
分為三種:Prefilters:預過濾器 、Postfilters:后過濾器 、Outputfilters:輸出過濾器
eg:
$smarty->assign("guolv","fff333 fff222 fff111"); function f3($data) {file_put_contents('./'.time().'.html', $data);return str_replace("fff333" , "333fff" , $data); } // 輸出過濾器 $smarty->registerFilter('output', 'f3' );
緩存
設置
$smarty->setCacheDir($cache_dir) // 設置緩存目錄,不設置默認cache文件中 $smarty->caching=true // 開啟緩存機制caching=true,默認為false $smarty->cache_lifetime = 120; // 緩存時間,單位為秒優(yōu)勢
1、速度要更快
2、減少服務器I/O開銷,減小服務器的壓力
3、減小對服務器數據庫的壓力
緩存在什么時候會重新生成
1、時間過期
2、緩存被刪除
3、編譯文件改變
4、模板文件改變
檢測模板有沒有被緩存
if($smarty->isCached("index.tpl")) {$smarty->display("index.tpl"); }刪除緩存的方式
$smarty->clearCache('tpl.tpl') // 清除指定模板緩存文件 $smarty->clearAll() // 清除所有緩存文件// 數據庫的增刪改之后,就要清除該緩存 // update后要清除的緩存 $smarty->clearCache("index.html"); //清除瀏覽緩存 $smarty->clearCache("edit.html",$_POST['id']); //清除修改表單緩存// 多級緩存 if(!$smarty->isCached("stu/edit.html",$_GET['id'])){$stu = $mod->find($_GET['id']);$smarty->assign("data",$stu); } $smarty->display("stu/edit.html",$_GET['id']);模板中局部緩存 (添加true參數)
// 方法一 , 刷新頁面會提示, $smarty->assign("linshi","linshi_huancun",true); {if empty($linshi)} no {else} yes-{$linshi} {/if}// 方法二 , 刷新頁面會提示, $smarty->assign("linshi","linshi_huancun",true); {nocache}{if empty($linshi)}no{else}yes-{$linshi}{/if}這一塊會緩存,不會緩存上面的變量 {/nocache}單頁面多緩存
當訪問某個頁面 news.php?id=5 時,第一次會查詢數據庫并緩存,之后就直接顯示緩存文件的內容,減小服務器、數據庫壓力// 只需要在display后面跟上id屬性 $smarty->display("index.tpl",$_GET['id']); // 結果 會在cache文件夾下,會根據id值多生成不同的緩存文件緩存集合
$smarty->display("index.tpl",$_GET['id'] . '|' . $_GET['page']); // 結果 同單頁面多緩存,會在cache文件夾下,根據多個條件生多生成多個的緩存文件 比如: 45^2^1a4de3f1e073e6a12c90ba07969d236f14.index.tpl.php 45^3^1a4de3f1e073e6a12c90ba07969d236f14.index.tpl.php 8^6^1a4de3f1e073e6a12c90ba07969d236f14.index.tpl.php結束
文章內容是邊學習邊寫示例代碼后做的筆記,初次上傳,有什么紕漏還望大家指正。
1、參考博客鏈接 - 參考鏈接
2、參考博客鏈接 - 參考鏈接
最后引用別人的一張圖片,感覺還不錯
總結
以上是生活随笔為你收集整理的smarty3.1.30 模板引擎的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spark 计算人员二度关系
- 下一篇: 带你了解关系网络在反欺诈领域的常见应用