天天看點

smarty2與smarty3的差別

smarty3和smarty2有許多的不同,但是關于smarty3的文檔非常少,并且有許多的錯誤,包括官方的smarty3的手冊中因為采用了smarty2的一些範例,也是錯誤的。

 以下知識點均針對smarty3

----compile_check:模闆編輯設定知識點如果将模闆編輯關閉($smarty->compile_check = false;),那麼修改模闆後也無法輸出最新的内容。如果想要得到最新的輸出,有兩種方法:1、将compile_check設定成true(預設)2、同時将對應的編譯模闆檔案(clearCompiledTemplate)和緩存檔案(clearCache)删除(如果開啟了緩存,如果緩存沒開啟,則不用)。 在調試的時候如果啟用了force_compile,那麼就每次都會重新編輯模闆(不管其是否更新,直接忽視compile_check限制),并且如果開啟了緩存,那麼每次都會重新生成緩存。 ----每面多個緩存  ----smarty3和smarty2的差別 擴充設定:請參考smarty3英文pdf文檔的擴充設定案例 動作函數名稱:格式由類似clear_all_cache()變成clearCache()、英文手冊中的例子中的$smarty->cache->clear應該是錯誤的。 ----緩存打開緩存(預設是關閉的): $smarty->caching  = Smarty::CACHING_LIFETIME_CURRENT;  //開啟緩存 $smarty->display("index.tpl","id");  //每頁多個緩存頁面 也可以在頁頭全局設定 $smarty->cache_id = "id",isCache和就可以不用設定了。 $smarty->isCache("index.tpl","id");  //判斷頁面是否緩存,用途:如果緩存已經存在則不讀取資料庫,反之亦然。一般背景如果有資料更新就會将對應的緩存删除。也可以在頁頭全局設定  

$smarty->cache_id = "id",isCache和就可以不用設定了。

首頁緩存一天

$Smarty->caching=true;$Smarty->cache_lifetime=86400;if(!$Smarty->is_cached('index.html')){ ...... } //文章頁 緩存 1周$Smarty->caching=true;$Smarty->cache_lifetime=7*86400;if(!$Smarty->is_cached('article.php',$id)){}

為了防止把執行速度也CACHE了

function nocache_block($params,$content,Smarty $Smarty){reurn$content;}$Smarty->register_block('nocache','nocache_block',false);

調用

<p> Processed in <!--{nocache}--><!--{$runtime}--><!--{/nocache}--></p>

引用另一種防止CACHE的方法

1、使用insert函數使模闆的一部分不被緩存

首先在php頁面中

<?phpfunction insert_get_now_time(){returndate("Y-m-d h:i:s",time()+3600*8);}     ?>//html調用方法現在時間為:<{insert name="get_now_time"}>

意:首先 函數命名一定要 以 insert_ 開頭 後面緊跟着 模版中的函數名字

隻要定義了函數 smarty 會自動 加載其函數 。

另一種

2使用register_function阻止插件從緩存中輸出

 index.tpl:<div>{current_time}</div> index.php:function smarty_function_current_time($params,&$smarty){returndate("Y-m-d H:m:s");} $smarty=new smarty();$smarty->caching=true;$smarty->register_function('current_time','smarty_function_current_time',false);if(!$smarty->is_cached()){.......}$smarty->display('index.tpl');

注解:

定義一個函數,函數名格式為:smarty_type_name($params,&$smarty)

type為function

name為使用者自定義标簽名稱,在這裡是{current_time}

兩個參數是必須的,即使在函數中沒有使用也要寫上。兩個參數的功能同上。