smarty是一個老牌Php模板引擎,作用是程序和美工分離(還沒遇到會用smarty的 美工,還是自己整合),緩存技術減輕了服務器的處理壓力。smarty緩存和頁面靜態化都是頁面緩存技術,區別是smarty緩存是臨時性的,靜態化是永 久性的,可以通過組合互補達到比較好的性能優化效果。而memcache是內存對象緩存系統,與前兩種比不是文件級別的緩存,而是內存級別的緩存。
配置:
1、在smarty官網下載最新文件包: http://www.smarty.net/,解壓縮文件包放到項目目錄下
2、新建一個php文件初始化smarty配置:
include_once("Smarty/Smarty.class.php"); //包含smarty類文件 $smarty = new Smarty(); //建立smarty實例對象$smarty $smarty->config_dir="Smarty/Config_File.class.php"; // 目錄變量 $smarty->caching=false; //是否使用緩存,項目在調試期間,不建議啟用緩存 $smarty->template_dir = "./templates"; //設置模板目錄 $smarty->compile_dir = "./templates_c"; //設置編譯目錄 $smarty->cache_dir = "./smarty_cache"; //緩存文件夾
3、在使用smarty的地方引用該配置文件
使用:
變量的使用:
php文件
$smarty->assign("模板變量", "值(數組/變量)"); $smarty->display("模板名稱");
htm文件
<html>
<title>{$name}</title>
常用變量操作符
capitalize [首字母大寫] count_characters [計算字符數] cat [連接字符串] count_paragraphs [計算段落數] count_sentences [計算句數] count_words [計算詞數] date_format [時間格式] default [默認] escape [轉碼] indent[縮進] lower[小寫 ] nl2br[換行符替換成<br />] regex_replace[正則替換] replace[替換] spacify[插空] string_format[字符串格式化] strip[去除(多余空格)] strip_tags[去除html標簽] truncate[截取] upper[大寫] wordwrap[行寬約束]
變量操作符使用語法
{$name|capitalize }
內置函數(判斷循環神馬的最常用了,你懂的)
1、判斷
{if $name=='ok'} {else} {/if}
2、循環
{foreach from=$name item=id} {$id} {/foreach} 或 {foreach key=j item=v from=$name } {$j}: {$v} {/foreach}
3、包含(引用頁面固定的頭尾都會用到的啦)
{include file="header.htm"}
4、沖突處理(頁面js用到大括號與smarty的大括號沖突怎么辦)
{literal} <script language=javascript> </script> {/literal}
literal數據將被當作文本處理,此時模板將忽略其內部的所有字符信息. 該特性用於顯示有可能包含大括號等字符信息的 javascript 腳本
另外,strip標記處理數據的首尾空格和回車,可以避免一些瀏覽器兼容性問題
smarty緩存的配置:
$smarty->cache_dir = "/caches/"; //緩存目錄 $smarty->caching = true; //開啟緩存,為flase的時侯緩存無效 $smarty->cache_lifetime = 60; //緩存時間
清除緩存:
$smarty->display('cache.tpl', cache_id); //創建帶ID的緩存 $smarty->clear_all_cache(); //清除所有緩存 $smarty->clear_cache('index.htm'); //清除index.tpl的緩存 $smarty->clear_cache('index.htm',cache_id); //清除指定id的緩存
神馬是帶ID的緩存,就是同一個模板頁面會顯示不同的內容,需要用id區別開來,生成不同的緩存文件。想ijiefang.com里面的商家首頁,都是同一個模板,但每個商家的內容都不同,需要一個商家首頁一個緩存文件。
局部緩存:
index.htm <div>{insert name="get_time"}</div> index.php function insert_get_time(){ return date("Y-m-d H:m:s"); } 或 {blockname} 沒有緩存的:{$smarty.now} {/blockname}