smarty

Smarty是一個php模板引擎。更準確的說,它分開了邏輯程序和外在的內容,提供了一種易於

管理的方法。可以描述爲應用程序員和美工扮演了不同的角色,因爲在大多數情況下,他們不

可能是同一個人。例如,你正在創建一個用於瀏覽新聞的網頁,新聞標題,標籤欄,作者和內容等

都是內容要素,他們並不包含應該怎樣去呈現。在Smarty的程序裏,這些被忽略了。模板設計

者們編輯模板,組合使用html標籤和模板標籤去格式化這些要素的輸出(html表格,背景色,字

體大小,樣式表,等等)。有一天程序員想要改變文章檢索的方式(也就是程序邏輯的改變)。這

個改變不影響模板設計者,內容仍將準確的輸出到模板。同樣的,哪天美工吃多了想要完全重

做界面,也不會影響到程序邏輯。因此,程序員可以改變邏輯而不需要重新構建模板,模板設計

者可以改變模板而不影響到邏輯。

smarty 不嘗試將邏輯完全和模板分開。如果邏輯程序嚴格的用於頁面表現,那麼它在模板裏

不會出現問題。有個建議:讓應用程序邏輯遠離模板,  頁面表現邏輯遠離應用程序邏輯。這將

在以後使內容更容易管理,程序更容易升級

Smarty的特點之一是"模板編譯"。意思是Smarty讀取模板文件然後用他們創建php腳本。

這些腳本創建以後將被執行。因此並沒有花費模板文件的語法解析,同時每個模板可以享受

到諸如Zend 加速 器(http://www.zend.com)  或者PHP 加速 器

(http://www.php-accelerator.co.uk)。這樣的php編譯器高速緩存解決方案。

Smaty的一些特點:

•  It is extremely fast.

非常非常的快!

•  It is efficient since the PHP parser does the dirty work.

用 php 分析器幹這個苦差事是有效的

•  No template parsing overhead, only compiles once.

不需要多餘的模板語法解析,僅僅是編譯一次

•  It is smart about recompiling only the template files that have

changed.

僅對修改過的模板文件進行重新編譯

•  You can make custom functionsand custom variable modifiers, so the

template language is extremely extensible.

可以編輯'自定義函數'和自定義'變量',因此這種模板語言完全可以擴展

•  Configurable template delimiter tag syntax, so you can use {}, {{}},

<!--{}-->, etc.

可以自行設置模板定界符,所以你可以使用{}, {{}}, <!--{}-->, 等等

•  The if/elseif/else/endif constructs are passed to the PHP parser,

so the {if ...} expression syntax can be as simple or as complex

as you like.

諸如 if/elseif/else/endif 語句可以被傳遞到 php 語法解析器,所以

{if ...} 表達式是簡單的或者是複合的,隨你喜歡啦

•  Unlimited nesting of sections, ifs, etc. allowed.

如果允許的話,section 之間可以無限嵌套

•  It is possible to embed PHP code right in your template files,

although this may not be needed (nor recommended) since the engine

is so customizable.

引擎是可以定製的.可以內嵌 php 代碼到你的模板文件中,雖然這可能並

不需要(不推薦)

•  Built-in caching support

內建緩存支持

•  Arbitrary template sources

獨立模板文件

•  Custom cache handling functions

可自定義緩存處理函數

•  Plugin architecture

插件體系結構

1.  官方網站下載smarty的版本,這裏以2.6.18爲基礎.解壓其中的libs,把libs 全部拷貝到

項目中

2.  下面是配置的代碼,新建個index.php文件,代碼爲:

<?php

//配置環境

include_once "libs/Smarty.class.php"; //引入smarty類文件

$smarty = new smarty();//初始化smarry

$smarty->template_dir = "template";// 設置模板目錄

$smarty->compile_dir = "template_c"; //設置編譯文件目錄

$smarty->cache_dir = "cache"; //設置  緩存目錄

$smarty->caching = false; //設置緩存開啓標誌

$smarty->cache_lifetime = "60"; //設置緩存有效時間

$smarty->left_delimiter = '{'; // 設置左分界符號

$smarty->right_delimiter = '}'; // 設置右分界符號

?>

3.在項目目錄中分別新建目錄template,template_c,cache,

整體目錄結構爲:

4.方法介紹

assign (name,value)

賦值 用來賦值到模板中。可以指定一對 名稱/數值 ,也可以指定包含 名稱/數值 的聯合數組。

例子:

// 名稱/數值 方式

$smarty->assign("Username","raojinpg");

$smarty->assign("Sex",$Sex);

// 聯合數組方式

$smarty->assign(array("city" => "jiangxi","state" => "nanchang"));

Fetch (tpl,cache_id,compile_id) 模板,緩存號,編譯號

取得輸出內容

// 捕獲輸出

$output = $smarty->fetch("index.tpl");

display (tpl,cache_id,compile_id)  模板,緩存號,編譯號

顯示

// 顯示

$smarty->display("index.tpl");

is_cached (tpl,cache_id)  模板,緩存號

是否被緩存

// 是否已經被緩存

$smarty->caching = true;

If(!$smarty->is_cached("index.tpl")){

$smarty->display("index.tpl");

}

//多緩存模板

$cache_id = sprintf(‘%X’,crc32($cache_id));

If(!$smarty->is_cached("index.tpl",$cache_id)){

$smarty->display("index.tpl",$cache_id);

}

clear_cache (tpl,cache_id,compile_id,inttime) 模板,緩存號,編譯號,超出時間

清除某一模板的緩存

//清除某一模板的緩存

$smarty->clear_cache("index.tpl");

//清除多緩存模板

$cache_id = sprintf(‘%X’,crc32($cache_id));

$smarty->clear_cache ("index.tpl",$cache_id)

clear_all_cache (inttime)超出時間

清除所有緩存

//清除所有緩存

$smarty-> clear_all_cache();

修飾符號

equal : 相等、------------------------------------------------ eq

not equal:不等於、-----------------------------------------ne neq

greater than:大於、-----------------------------------------gt

less than:小於、---------------------------------------------lt

less than or equal:小於等於、----------------------------lte ,le

great than or equal:大於等於、---------------------------gte ,ge

is even:是偶數、

is odd:是奇數、

is not even:不是偶數、

is not odd:不是奇數、

not:非、

mod:取餘、

div by:被。。。除

==、!=、>、<、<=、>=

變量調節器

* capitalize [首字符大寫]

* count_characters [字符計數]

* cat [連接字符串] cat裏的值連接到給定的變量後面.

* count_characters[字符計數] {$articleTitle|count_characters:true}決定是否計算空格字符。

* count_sentences[計算句數]

* count_words[計算詞數]

* date_format[格式化日期] {$smarty.now|date_format:"%H:%M:%S"}

* default[默認值] {$myTitle|default:"no title"}

* escape[編碼] html,htmlall,url,quotes,hex,hexentity,javascript {$articleTitle|escape:"url"}

* indent[縮進] 在每行縮進字符串,默認是4個字符

* lower [小寫]

* nl2br [換行符替換成<br />]

* regex_replace [正則替換] {$articleTitle|regex_replace:"/[\r\t\n]/":" "}

* replace [替換]

* spacify [插空]

* string_format [字符串格式化]

* strip [去除(多餘空格)]

* strip_tags [去除html標籤]

* truncate [截取]

* upper [大寫]

* wordwrap [行寬約束]

函數

Capture

capture函數的作用是捕獲模板輸出的數據並將其存儲到一個變量裏,而不是把它們輸出到頁面.

任何在{capture name="name"}和{/capture}之間的數據將被存儲到變量$name中,該變量由name屬性指定.

在模板中通過$smarty.capture.name 訪問該變量.

如果沒有指定name 屬性,函數默認將使用"default" 作爲參數.

{capture}必須成對出現,即以{/capture}作爲結尾,該函數不能嵌套使用.

當希望捕獲包含  {insert} 命令的數據時要特別注意.  如果打開了緩存並希望將 {insert} 命令輸出到緩中,

不要捕獲該區域的數據

{* 該例在捕獲到內容後輸出一行包含數據的表格,如果沒有捕獲到就什麼也不輸出 *}

{capture name=banner}{include file="get_banner.tpl"}{/capture}

{if $smarty.capture.banner ne ""}{$smarty.capture.banner}{/if}

Config_load

該函數用於從配置文件中加載變量{config_load file="colors.conf"}  使用{#變量#}

配置文件內容

配置文件內容

# global variables

pageTitle = "Main Menu"

bodyBgColor = #000000

tableBgColor = #000000

rowBgColor = #00ff00

[Customer]

pageTitle = "Customer Info"

[Login]

pageTitle = "Login"

focus = "username"

Intro = """This is a value that spans more

than one line. you must enclose

it in triple quotes."""

# hidden section

[.Database]

host=my.domain.com

db=ADDRESSBOOK

user=php-user

pass=foobar

///////////////////////////////////////////////模板文件內容

{config_load file="colors.conf"}

<html>

<title>{#pageTitle#}</title>

<body bgcolor="{#bodyBgColor#}">

<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">

<tr bgcolor="{#rowBgColor#}">

<td>First</td>

<td>Last</td>

<td>Address</td>

</tr>

</table>

</body>

</html>

帶section 屬性的config_load 函數演示

{config_load file="colors.conf" section="Customer"}

<html>

<title>{#pageTitle#}</title>

<body bgcolor="{#bodyBgColor#}">

<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">

<tr bgcolor="{#rowBgColor#}">

<td>First</td>

<td>Last</td>

<td>Address</td>

</tr>

</table>

</body>

</html>

PHP

允許模板使用PHP語法

{php}

echo time();

{/php}

Literal

標籤區域內的數據將被當作文本處理,此時模板將忽略其內部的所有字符信息.  該特性用於顯示有可能包

含大括號等字符信息的javascript 腳本

{literal}

<script>

function fun(){

alert(1);

}

</script>

{/literal}

include

Include 標籤用於在當前模板中包含其它模板.  當前模板中的變量在被包含的模板中可用.  必須指定file

屬性,該屬性指明模板資源的位置.

{include file="header.tpl"}

//可以帶參數,

{include file="header.tpl" title="標題"}

Insert

所包含的內容不會被緩存,每次調用該模板都會重新執行該函數.

//php 代碼

<?php

Function insert_nocache($array){

//Return time();

Print_r($array);

}

?>

//模板代碼

{insert name="nocache" tid="2"}

ldelim,rdelim

ldelim 和rdelim 用於輸出分隔符,也就是大括號"{" 和"}". 模板引擎總是嘗試解釋大括號內的內容,因

此如果需要輸出大括號,請使用此方法

if,elseif,else

if 必須於/if 成對出現. 可以使用else 和elseif 子句

{if $name eq "Fred"}

Welcome Sir.

{elseif $name eq "Wilma"}

Welcome Ma'am.

{else}

Welcome, whatever you are.

{/if}

foreach,foreachelse

foreach 是除section 之外處理循環的另一種方案(根據不同需要選擇不同的方案).

foreach 用於處理簡單數組(數組中的元素的類型一致),它的格式比section 簡單許多,缺點是隻能處理簡

單數組.

foreach 必須和/foreach 成對使用,且必須指定from 和item 屬性.

name 屬性可以任意指定(字母、數字和下劃線的組合).

foreach 可以嵌套,但必須保證嵌套中的foreach 名稱唯一.

from 屬性(通常是數組)決定循環的次數.

foreachelse 語句在from 變量沒有值的時候被執行.

{* 該例將輸出數組 $custid 中的所有元素的值 *}

//php 代碼

$smarty->assign('custid',range(1,3));

//tpl

{foreach from=$custid item=curr_id}

id: {$curr_id}<br>

{/foreach}

OUTPUT:

id: 1<br>

id: 2<br>

id: 3<br>.

{*多唯*}

//php 代碼

$smarty->assign("contacts",

array(array("phone" => "1", "fax" => "2", "cell" => "3"),

array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")));

{* 鍵就是數組的下標,請參看關於數組的解釋 *}

//tpl

{foreach name=outer item=contact from=$contacts}

{foreach key=key item=item from=$contact}

{$key}: {$item}<br>

{/foreach}

{/foreach}

OUTPUT:

phone: 1<br>

fax: 2<br>

cell: 3<br>

phone: 555-4444<br>

fax: 555-3333<br>

cell: 760-1234<br>

section,sectionelse

section 用於遍歷數組中的數據.  section  標籤必須成對出現.  必須設置  name  和  loop 屬性.  名稱可以是包

含字母、數字和下劃線的任意組合.  可以嵌套但必須保證嵌套的name 唯一.  變量loop (通常是數組)決定

循環執行的次數.  當需要在section 循環內輸出變量時,必須在變量後加上中括號包含着的name 變量.

sectionelse 當loop 變量無值時被執行

index:用於顯示當前循環的索引,從0開始(如果指定了start屬性,那麼由該值開始),每次加1(如果指定了

step屬性,那麼由該值決定).如果沒有指定step和start屬性,此值的作用和iteration類似,只不過從0開始

而已.

index_prev:用於顯示上一個循環索引值. 循環開始時,此值爲-1.

index_next:用於顯示下一個循環索引值.  循環執行到最後一次時,此值仍然比當前索引值大1(如果指定了

step,取決於此值).

iteration:用於顯示循環的次數.iteration 不像index屬性受start、step和max屬性的影響,該值總是從1開始

(index是從0開始的).rownum 是iteration的別名,兩者等同.

first:如果當前循環第一次執行,first 被設置爲true.

last:如果當前循環執行到最後一次,last 被設置爲true.

rownum:用於顯示循環的次數. 該屬性是iteration的別名,兩者等同.

loop:用於顯示該循環上一次循環時的索引值. 該值可以用於循環內部或循環結束後.

show:是section 的參數. show 取值爲布爾值true 或false. 如果設置爲false,該循環將不顯示. 如果指定

了sectionelse 子句,該字句是否顯示也取決於該值.

total:用於顯示循環執行總的次數. 可以在循環中或執行結束後調用此屬性.

//一維

{section name=item loop=$array2}

值爲:{$array2[item]}

{$item}

{/section}

//一維

{section name=n loop=$people}

name:{$people[n]}<br/>

{/section}

//關聯數組

{section name=sn loop=$news}

{if $smarty.section.sn.first}

<table>

<th>id</th>

<th>title</th>

{/if}

<tr>

<td>{$news[sn].id}</td>

<td>{$news[sn].title}</td>

</tr>

{if $smarty.section.sn.last}

</table>

{/if}

{sectionelse}

there is no news.

{/section}

strip

Smarty 在顯示前將除區任何位於{strip}{/strip} 標記中數據的首尾空格和回車.  這樣可以保證模板容易理

解且不用擔心多餘的空格導致問題

擴展方法

在smarty中帶了比較多的內部方法,如果我們要擴展一個capitalize類似的方法那如何做呢

假定我們的方法爲checkemail

首先建立個文件,名稱爲modifier. checkemail.php

然後代碼爲

<?php

Function smarty_checkemail($string){

//這裏做你自己需要處理的事情

}

?>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章