Smarty模板變量與調(diào)節(jié)器實(shí)例詳解
本文實(shí)例講述了Smarty模板變量與調(diào)節(jié)器。分享給大家供大家參考,具體如下:
Smarty中assign說明
可能有人在學(xué)習(xí)smarty的時候已經(jīng)學(xué)習(xí)了一些php框架,如tp、laravel、Yii等,這里拿tp框架的assign和smarty做一些比較。
$name=thinkphp; $this->assign('name',$name); $this->display();
$smarty=new Smarty(); $smarty->assign('name','smarty'); $smarty->display(index.tpl);
上面兩段代碼片分別是tp和smarty(千萬別混淆tp和smarty,一個是開源的框架,一個是模板設(shè)計引擎)。
tp在視圖模塊調(diào)用是 {$name}{$name},等同于php里的, <?php echo($name);?>,smarty中是在index.tpl用{$name}調(diào)用。注意模板標(biāo)簽的{和$之間不能有任何的空格,否則標(biāo)簽無效。
數(shù)組變量
$smarty = new Smarty; $smarty->assign('smarty', array('name'=>'smarty' 'user' => 'sm'))); $smarty->display('index.tpl');
index.tpl
{$smarty.name}<br> {$smarty.user}<br>
<?php $smarty->assign('data', array( 'smarty', 'sm', )); $smarty->display('index.tpl'); ?>
index.tpl source:
{$Contacts[0]}<br /> {$Contacts[1]}<br />
在tp中的調(diào)用有兩種方法,如下:
$data[name]='thinkphp'; $data[user]='tp'; $this->a``ssign('data',$data);
這里視圖調(diào)用有兩種方法:
Name:{$data.name} user:{$data.user}
name:{$data['name']} name:{$data['user']}
同理對象如下所示:
首先是smarty:
name: {$data->name}<br> user: {$data->user}<br>
tp:
$data->name='thinkphp'; $data->user='tp'; $this->assign('data',$data); $this->display();
也有兩種調(diào)用方式:
name:{$data->name} user:{$data->user}
name:{$data:name} user:{$data:user}
smaty和thinkphp是不是有異曲同工之妙呢,所以我們學(xué)習(xí)框架之前學(xué)習(xí)smarty是很有幫助的。
變量調(diào)節(jié)器
為什么先講調(diào)節(jié)器呢,因?yàn)槲矣X得這部分其一比較通俗簡單,其二后面一些內(nèi)容也會涉及到調(diào)節(jié)器的內(nèi)容。按我的理解smarty的內(nèi)置調(diào)節(jié)器就如同php里面內(nèi)置函數(shù)一樣起簡化編程的作用。
調(diào)節(jié)器一般用法
變量調(diào)節(jié)器作用于變量、自定義函數(shù)或字符串。變量調(diào)節(jié)器的用法是:‘|'符號右接調(diào)節(jié)器名稱。變量調(diào)節(jié)器可接收附加參數(shù)影響其行為。參數(shù)位于調(diào)節(jié)器右邊,并用‘:'符號分開。
capitalize
變量所有單詞首字母大寫作用,和php的ucword()
作用相同。
<?php$smarty->assign('articleTitle', 'next x-men film, x3, delayed.');?>
//Where the template is: {$articleTitle} {$articleTitle|capitalize} {$articleTitle|capitalize:true}
//Will output:
next x-men film, x3, delayed.
Next X-Men Film, x3, Delayed.
Next X-Men Film, X3, Delayed.
cat
將cat里的值后接到給定的變量后面。
<?php$smarty->assign('articleTitle', "Psychics predict world didn't end");?>
//index.tpl: {$articleTitle|cat:" yesterday."}
//OUTPUT:
Psychics predict world didn't end yesterday.
count_characters
<?php $smarty->assign('articleTitle', 'Cold Wave Linked to Temperatures.'); ?>
//Where template is: {$articleTitle} {$articleTitle|count_characters}//默認(rèn)是false不計算空格 {$articleTitle|count_characters:true}//true確定計算空格字符。
//Will output:
Cold Wave Linked to Temperatures.
29
33
count_paragraphs,count_sentences,count_words
分別是計算變量里的段落數(shù)量,計算變量里句子的數(shù)量,計算變量里的詞數(shù)作用,這里不一一舉例。
default
為變量設(shè)置一個默認(rèn)值。當(dāng)變量未設(shè)置或?yàn)榭兆址畷r,將由給定的默認(rèn)值替代其輸出。Default需要一個參數(shù)。
<?php$smarty->assign('articleTitle', 'Dealers Will Hear Car Talk at Noon.'); $smarty->assign('email', '');?>
//Where template is: {$articleTitle|default:'no title'} {$myTitle|default:'no title'} {$email|default:'No email address available'}
//Will output:
Dealers Will Hear Car Talk at Noon.
no title
Noemail address available
lower和upper
這里不想講多少,一個是將字符串小寫,一個大寫。
replace和regex_replace
使用正則表達(dá)式在變量中搜索和替換,語法來自Php的preg_repalce函數(shù)。一種在變量中進(jìn)行簡單的搜索和替換字符串的處理。等同于php的str_replace()函數(shù)。 不懂得去看php手冊。雖然Smarty支持regex正則調(diào)節(jié)器,但最好還是直接使用php的正則表達(dá)式,要么使用自定義函數(shù)或調(diào)節(jié)器。因?yàn)檎齽t法則屬于程序代碼,其并不認(rèn)為是內(nèi)容外在表現(xiàn)的一部份。
date_format和string_format
主要說明一下這兩個調(diào)節(jié)器。
date_format
本調(diào)節(jié)器將格式化的日期和時間經(jīng)php函數(shù)strftime()
處理。Unix時間戳、mysql時間戳及由年月日組成的字符串格式的日期可以傳遞到smarty經(jīng)php函數(shù)strtotime()解析。設(shè)計者可以使用date_format完全控制日期格式,如果傳給date_format的日期為空值,但提供了第二個參數(shù),那么將使用第二參數(shù)格式化時間。
從Smarty-2.6.10開始,傳遞給date_format的數(shù)字值(除了mysql時間戳,見下文)總是當(dāng)作unix時間戳。
在2.6.10版本之前,符合時間戳格式的數(shù)字型字符串(如YYYYMMDD)同樣可以經(jīng)由php函數(shù)strtotime()處理,因?yàn)橛袝r(取決于strtotime()的底層實(shí)現(xiàn))strtotime()接收日期字符串參數(shù),而不是時間戳。
唯一的例外是mysql時間戳:它們本身只有數(shù)字,并且是14個字符的長度(YYYYMMDDHHMMSS),mysql時間戳優(yōu)先于unix時間戳。
<?php $config['date'] = '%I:%M %p'; $config['time'] = '%H:%M:%S'; $smarty->assign('config', $config); $smarty->assign('yesterday', strtotime('-1 day')); ?>
//This template uses $smarty.now to get the current time: {$smarty.now|date_format} {$smarty.now|date_format:"%D"} {$smarty.now|date_format:$config.date} {$yesterday|date_format} {$yesterday|date_format:"%A, %B %e, %Y"} {$yesterday|date_format:$config.time}
//This above will output:
Jan 1, 2022
01/01/22
02:33 pm
Dec 31, 2021
Monday, December 1, 2021
14:33:00
date_format轉(zhuǎn)換標(biāo)記:
%a - 當(dāng)前區(qū)域星期幾的簡寫
%A - 當(dāng)前區(qū)域星期幾的全稱
%b - 當(dāng)前區(qū)域月份的簡寫
%B - 當(dāng)前區(qū)域月份的全稱
%c - 當(dāng)前區(qū)域首選的日期時間表達(dá)
%C - 世紀(jì)值(年份除以 100 后取整,范圍從 00 到 99)
%d - 月份中的第幾天,十進(jìn)制數(shù)字(范圍從 01 到 31)
%D - 和 %m/%d/%y 一樣
%e - 月份中的第幾天,十進(jìn)制數(shù)字,一位的數(shù)字前會加上一個空格(范圍從 ' 1' 到 ‘31')
%g - 和 %G 一樣,但是沒有世紀(jì)
%G - 4 位數(shù)的年份,符合 ISO 星期數(shù)(參見 %V)。和 %V 的格式和值一樣,只除了如果 ISO 星期數(shù)屬于前一年或者后一年,則使用那一年。
%h - 和 %b 一樣
%H - 24 小時制的十進(jìn)制小時數(shù)(范圍從 00 到 23)
%I - 12 小時制的十進(jìn)制小時數(shù)(范圍從 00 到 12)
%j - 年份中的第幾天,十進(jìn)制數(shù)(范圍從 001 到 366)
%m - 十進(jìn)制月份(范圍從 01 到 12)
%M - 十進(jìn)制分鐘數(shù)
%n - 換行符
%p - 根據(jù)給定的時間值為 am' 或pm',或者當(dāng)前區(qū)域設(shè)置中的相應(yīng)字符串
%r - 用 a.m. 和 p.m. 符號的時間
%R - 24 小時符號的時間
%S - 十進(jìn)制秒數(shù)
%t - 制表符
%T - 當(dāng)前時間,和 %H:%M:%S 一樣
%u - 星期幾的十進(jìn)制數(shù)表達(dá) [1,7],1 表示星期一
%U - 本年的第幾周,從第一周的第一個星期天作為第一天開始
%V - 本年第幾周的 ISO 8601:1988 格式,范圍從 01 到 53,第 1 周是本年第一個至少還有 4 天的星期,星期一作為每周的第一天。(用 %G 或者 %g 作為指定時間戳相應(yīng)周數(shù)的年份組成。)
%W - 本年的第幾周數(shù),從第一周的第一個星期一作為第一天開始
%w - 星期中的第幾天,星期天為 0
%x - 當(dāng)前區(qū)域首選的時間表示法,不包括時間
%X - 當(dāng)前區(qū)域首選的時間表示法,不包括日期
%y - 沒有世紀(jì)數(shù)的十進(jìn)制年份(范圍從 00 到 99)
%Y - 包括世紀(jì)數(shù)的十進(jìn)制年份
%Z 或 %z - 時區(qū)名或縮寫
%% - 文字上的 `%' 字符
string_format
一種格式化字符串的方法,例如格式化為十進(jìn)制數(shù)等等。實(shí)際運(yùn)用的是php的sprintf()
函數(shù)。
<?php $smarty->assign('number', 23.5787446); ?>
//Where template is: {$number} {$number|string_format:"%.2f"} {$number|string_format:"%d"}
//Will output:
23.5787446
23.58
24
獲取配置文件變量
加載配置文件后,配置文件中的變量需要用兩個井號”#”包圍或者是smarty的保留變量$smarty.config.來調(diào)用(下節(jié)將講到),第二種語法在變量作為屬性值嵌入至引號的時候非常有用,詳細(xì)可參考雙引號里值的嵌入。
假如配置文件如下:
//config file - foo.conf: pageTitle = "This is mine" bodyBgColor = '#eeeeee' tableBorderSize = 3 tableBgColor = "#bbbbbb" rowBgColor = "#cccccc"
調(diào)用方法如下:
{config_load file='foo.conf'}//{config_load}是一個smarty內(nèi)置函數(shù)。用來從配置文件中加載config變量(#variables#)到模版 <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>
保留變量
我們一般訪問環(huán)境變量的時候就使用保留變量{$smarty}。
請求變量諸如GET,GET,_POST,COOKIE,COOKIE,_SERVER, ENVandENVand_SESSION (參考requestvarsorder和requestvarsorder和request_use_auto_globals) 下面舉例說明他們的用法:
//http://www.example.com/index.php?page=fo {$smarty.get.page}//從URL獲取page的值,等價于$_GET['page'] {$smarty.post.page}//獲取page的變量,等價于$_POST['page'] {$smarty.cookies.username}//獲取cookie信息,等價于$_COOKIE['username'] {$smarty.env.PATH}//獲取PATG環(huán)境變量 {$smarty.session.id}//獲取會話變量,等價于$_SESSION['id'] {$smarty.request.username}
盡管Smarty提供了直接訪問php超級變量的便利,但仍需謹(jǐn)慎使用。一般來說,GET、POST和REQUEST通常用來直接取值,但更常用的方法是通過訪問SERVER、ENV、COOKIE、SESSION變量以防止(不安全值)混進(jìn)模版底層代碼。一個好的習(xí)慣是給模板變量賦具體的初始值。
1.{$smarty.now}
返回自從Unix 紀(jì)元(格林威治時間 1970 年1月1日00:00:00)到當(dāng)前時間的秒數(shù),可以直接通過變量調(diào)節(jié)器date_format輸出顯示。應(yīng)注意的是time()在每次觸發(fā)時被調(diào)用;例如,腳本執(zhí)行完需要3秒鐘,在始末分別調(diào)用$smarty.now的話將顯示3秒的差異。
{$smarty.now|date_format:'%Y-%m-%d %H:%M:%S'}
2.{#smarty.const}
訪問php常量
<?php// the constant defined in phpdefine('MY_CONST_VAL','CHERRIES');?> //Output the constant in a template with{$smarty.const.MY_CONST_VAL} <?php // php定義常量 define('MY_CONST_VAL','CHERRIES');?>
3.{$smarty.capture}
可以通過{$smarty.capture}
變量捕獲內(nèi)置的{capture}…{/capture}
模版輸出。
4.{$smarty.config}
獲取配置變量
5.{$smarty.section}
{$smarty.section}
用來指向{section}
循環(huán)的屬性,里面包含一些有用的值,比如.first/.index等。
6.{$smarty.template}
返回經(jīng)過處理的當(dāng)前模板名(不包括目錄)。
7.{$smarty.current_dir}
返回經(jīng)過處理的當(dāng)前模板目錄名。
8{$smarty.version}、$smarty.block.child}、{$smarty.block.parent}{$smarty.ldelim}、{$smarty.rdelim}
用的少,不作說明,可以查看手冊了解更多內(nèi)容。
更多關(guān)于Smarty相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《smarty模板入門基礎(chǔ)教程》、《PHP模板技術(shù)總結(jié)》、《PHP基于pdo操作數(shù)據(jù)庫技巧總結(jié)》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP基本語法入門教程》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于smarty模板的PHP程序設(shè)計有所幫助。
相關(guān)文章
PHP中通過exec調(diào)用python腳本報ModuleNotFoundError錯誤問題及解決方法
這篇文章主要介紹了解決php中通過exec調(diào)用python腳本報ModuleNotFoundError錯誤,本文是在 Ubuntu 20.04 上以 ubuntu 用戶身份進(jìn)行的測試,需要的朋友可以參考下2023-07-07Zend Framework實(shí)現(xiàn)具有基本功能的留言本(附demo源碼下載)
這篇文章主要介紹了Zend Framework實(shí)現(xiàn)具有基本功能的留言本,結(jié)合實(shí)例形式較為詳細(xì)的分析了Zend Framework實(shí)現(xiàn)留言本的具體步驟與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-03-03ThinkPHP設(shè)置禁止百度等搜索引擎轉(zhuǎn)碼(簡單實(shí)用)
這篇文章主要介紹了ThinkPHP設(shè)置禁止百度等搜索引擎轉(zhuǎn)碼(簡單實(shí)用)的相關(guān)資料,需要的朋友可以參考下2016-02-02ThinkPHP實(shí)現(xiàn)微信支付(jsapi支付)流程教程詳解
這篇文章主要介紹了ThinkPHP實(shí)現(xiàn)微信支付(jsapi支付)流程教程詳解,需要的朋友可以參考下2018-03-03