本文實例講述了smarty模板的使用方法。分享給大家供大家參考,具體如下:
這里以smarty3為例
首先, 在官網下載smarty3模板文件,然后解壓。
在解壓之后的文件夾中,libs是smarty模板的核心文件,demo里面有示例程序。
我們把libs文件夾復制到我們的工作目錄,然后重命名為smarty。
假設我們在controller目錄下的index.php中使用smarty模板。
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?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
1
2
3
4
5
6
7
8
9
10
11
|
< html > < head > < title ></ title > </ head > < body > < p >< h1 ><{$name}></ h1 ></ p > <{foreach $list as $k=>$v }> < p >< h1 ><{$k}> : <{$v}></ h1 ></ p > <{/foreach}> </ body > </ html > |
上述方法的優點是使用起來配置比較簡單,缺點也是顯而易見的,我們controller目錄下可能有很多頁面調用smarty模板,在每個頁面都需要將上述方法配置一遍。
解決方法有兩種:
將smarty模板的配置信息寫到一個文件中,然后其他頁面可以通過包含該文件使用smarty對象。
1
2
3
4
5
6
7
8
9
10
11
|
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類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?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代碼可優化為:
1
2
3
4
5
6
7
|
<?php require 'mySmarty.php' ; $smarty = new mySmarty; $list = range( 'A' , 'D' ); $smarty ->assign( "list" , $list ); $smarty ->assign( "name" , "zhezhao" ); $smarty ->display( 'index.html' ); |
最后送上福利:smarty3 chm官方文檔。
希望本文所述對大家基于smarty模板的PHP程序設計有所幫助。
原文鏈接:https://blog.csdn.net/koastal/article/details/51423125