環(huán)境:
smarty
1.在http://www.smarty.net/download下載最新smarty包,window選擇zips,linux下選擇tar.gz。以windows為例,下載后解壓,如f:/smarty。
2.把解壓出來的smarty目錄里lib目錄拷貝到test里,重命名為smarty。在test目錄下,創(chuàng)建tpls目錄,在tpls目錄下,創(chuàng)建templates、templates_c、configs、cache目錄,這幾個目錄分別是模板目錄(必要),解析目錄(必要),配置目錄(可選),緩存目錄(可選),
smarty的php代碼和這四個目錄是同一個級的,html代碼放在templates下。
目錄樹如下
代碼部分:
1.在test/smarty下創(chuàng)建utf-8無bom格式的main.php,配置smarty的一些成員屬性。
1 <?php 2 include("Smarty.class.php"); 3 define('SMARTY_ROOT', '../tpls'); 4 $tpl = new Smarty(); 5 $tpl->template_dir = SMARTY_ROOT."/templates/";//設置模板文件的存放目錄 6 $tpl->compile_dir = SMARTY_ROOT."/templates_c/";//設置編譯文件的存放目錄 7 $tpl->config_dir = SMARTY_ROOT."/configs/";//設置配置文件的存放目錄 8 $tpl->cache_dir = SMARTY_ROOT."/cache/";//設置緩存文件的存放目錄 9 $tpl->caching=1;//開啟緩存10 $tpl->cache_lifetime=60*60*24;//有效時間為一天11 $tpl->left_delimiter = '[';//smarty語言的左右結束符12 $tpl->right_delimiter = ']';13 ?>
我們知道大括號是smarty的默認定界符,但在和javascript、CSS等結合時可能會產(chǎn)生沖突,所以這里我們設定為[和]。
2.在test/tpls/templates下面新建html.tpl模板文件,就是在html中加入smarty變量。改模板相當于表現(xiàn)層。
html.tpl的代碼如下:
1 <html> 2 <head> 3 <meta http-equiv="Content-type" content="text/html; charset=utf-8"> 4 <title> 5 [$title] 6 </title> 7 </head> 8 <body> 9 [$content]10 </body> 11 </html>
3.在test目錄下創(chuàng)建smarty.php,該文件相當于驅動層,給上面表現(xiàn)層的變量賦好值,然后顯示出來。
smarty.php的代碼如下:
1 <?php2 include("smarty/main.php");3 $tpl->assign("title","遲到");4 $tpl->assign("content","罰款500元!");5 $tpl->display("tpls/templates/html.tpl");6 ?>
4.在瀏覽器中運行smarty.php即可。
新聞熱點
疑難解答