Smarty變量與調節器詳解

Smarty中assign說明

可能有人在學習smarty的時候已經學習了一些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,一個是開源的框架,一個是模板設計引擎)。
tp在視圖模塊調用是 {$name}{$name},等同於php裏的, <?php echo($name);?>,smarty中是在index.tpl用{$name}調用。注意模板標籤的{和$之間不能有任何的空格,否則標籤無效。

數組變量

$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中的調用有兩種方法,如下:

$data[name]='thinkphp';
$data[user]='tp';
$this->a``ssign('data',$data);

這裏視圖調用有兩種方法:

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();

也有兩種調用方式:

name:{$data->name}
user:{$data->user}
name:{$data:name}
user:{$data:user}

smaty和thinkphp是不是有異曲同工之妙呢,所以我們學習框架之前學習smarty是很有幫助的。

變量調節器

爲什麼先講調節器呢,因爲我覺得這部分其一比較通俗簡單,其二後面一些內容也會涉及到調節器的內容。按我的理解smarty的內置調節器就如同php裏面內置函數一樣起簡化編程的作用。

調節器一般用法

變量調節器作用於變量、自定義函數或字符串。變量調節器的用法是:‘|’符號右接調節器名稱。變量調節器可接收附加參數影響其行爲。參數位於調節器右邊,並用‘:’符號分開。

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}//默認是false不計算空格
{$articleTitle|count_characters:true}//true確定計算空格字符。

//Will output:

Cold Wave Linked to Temperatures.
29
33 

count_paragraphs,count_sentences,count_words

分別是計算變量裏的段落數量,計算變量裏句子的數量,計算變量裏的詞數作用,這裏不一一舉例。

default

爲變量設置一個默認值。當變量未設置或爲空字符串時,將由給定的默認值替代其輸出。Default需要一個參數。

<?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

使用正則表達式在變量中搜索和替換,語法來自Php的preg_repalce函數。一種在變量中進行簡單的搜索和替換字符串的處理。等同於php的str_replace()函數。 不懂得去看php手冊。雖然Smarty支持regex正則調節器,但最好還是直接使用php的正則表達式,要麼使用自定義函數或調節器。因爲正則法則屬於程序代碼,其並不認爲是內容外在表現的一部份。

date_format和string_format

主要說明一下這兩個調節器。

date_format

本調節器將格式化的日期和時間經php函數strftime()處理。Unix時間戳、mysql時間戳及由年月日組成的字符串格式的日期可以傳遞到smarty經php函數strtotime()解析。設計者可以使用date_format完全控制日期格式,如果傳給date_format的日期爲空值,但提供了第二個參數,那麼將使用第二參數格式化時間。
從Smarty-2.6.10開始,傳遞給date_format的數字值(除了mysql時間戳,見下文)總是當作unix時間戳。
在2.6.10版本之前,符合時間戳格式的數字型字符串(如YYYYMMDD)同樣可以經由php函數strtotime()處理,因爲有時(取決於strtotime()的底層實現)strtotime()接收日期字符串參數,而不是時間戳。
唯一的例外是mysql時間戳:它們本身只有數字,並且是14個字符的長度(YYYYMMDDHHMMSS),mysql時間戳優先於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轉換標記:

%a - 當前區域星期幾的簡寫
%A - 當前區域星期幾的全稱
%b - 當前區域月份的簡寫
%B - 當前區域月份的全稱
%c - 當前區域首選的日期時間表達
%C - 世紀值(年份除以 100 後取整,範圍從 00 到 99)
%d - 月份中的第幾天,十進制數字(範圍從 01 到 31)
%D - 和 %m/%d/%y 一樣
%e - 月份中的第幾天,十進制數字,一位的數字前會加上一個空格(範圍從 ’ 1’ 到 ‘31’)
%g - 和 %G 一樣,但是沒有世紀
%G - 4 位數的年份,符合 ISO 星期數(參見 %V)。和 %V 的格式和值一樣,只除了如果 ISO 星期數屬於前一年或者後一年,則使用那一年。
%h - 和 %b 一樣
%H - 24 小時制的十進制小時數(範圍從 00 到 23)
%I - 12 小時制的十進制小時數(範圍從 00 到 12)
%j - 年份中的第幾天,十進制數(範圍從 001 到 366)
%m - 十進制月份(範圍從 01 到 12)
%M - 十進制分鐘數
%n - 換行符
%p - 根據給定的時間值爲 am' 或pm’,或者當前區域設置中的相應字符串
%r - 用 a.m. 和 p.m. 符號的時間
%R - 24 小時符號的時間
%S - 十進制秒數
%t - 製表符
%T - 當前時間,和 %H:%M:%S 一樣
%u - 星期幾的十進制數表達 [1,7],1 表示星期一
%U - 本年的第幾周,從第一週的第一個星期天作爲第一天開始
%V - 本年第幾周的 ISO 8601:1988 格式,範圍從 01 到 53,第 1 周是本年第一個至少還有 4 天的星期,星期一作爲每週的第一天。(用 %G 或者 %g 作爲指定時間戳相應週數的年份組成。)
%W - 本年的第幾週數,從第一週的第一個星期一作爲第一天開始
%w - 星期中的第幾天,星期天爲 0
%x - 當前區域首選的時間表示法,不包括時間
%X - 當前區域首選的時間表示法,不包括日期
%y - 沒有世紀數的十進制年份(範圍從 00 到 99)
%Y - 包括世紀數的十進制年份
%Z 或 %z - 時區名或縮寫
%% - 文字上的 `%’ 字符

string_format

一種格式化字符串的方法,例如格式化爲十進制數等等。實際運用的是php的sprintf()函數。

<?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.來調用(下節將講到),第二種語法在變量作爲屬性值嵌入至引號的時候非常有用,詳細可參考雙引號裏值的嵌入。
假如配置文件如下:

//config file - foo.conf:

pageTitle = "This is mine"
bodyBgColor = '#eeeeee'
tableBorderSize = 3
tableBgColor = "#bbbbbb"
rowBgColor = "#cccccc"

調用方法如下:

{config_load file='foo.conf'}//{config_load}是一個smarty內置函數。用來從配置文件中加載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> 

保留變量

我們一般訪問環境變量的時候就使用保留變量{$smarty}
請求變量諸如GET, _POST,COOKIE, _SERVER, ENVand _SESSION (參考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環境變量
{$smarty.session.id}//獲取會話變量,等價於$_SESSION['id']
{$smarty.request.username}

儘管Smarty提供了直接訪問php超級變量的便利,但仍需謹慎使用。一般來說,GET、POST和REQUEST通常用來直接取值,但更常用的方法是通過訪問SERVER、ENV、COOKIE、SESSION變量以防止(不安全值)混進模版底層代碼。一個好的習慣是給模板變量賦具體的初始值。

1.{$smarty.now}

返回自從Unix 紀元(格林威治時間 1970 年1月1日00:00:00)到當前時間的秒數,可以直接通過變量調節器date_format輸出顯示。應注意的是time()在每次觸發時被調用;例如,腳本執行完需要3秒鐘,在始末分別調用$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}變量捕獲內置的{capture}…{/capture}模版輸出。

4.{$smarty.config}

獲取配置變量

5.{$smarty.section}

{$smarty.section}用來指向{section}循環的屬性,裏面包含一些有用的值,比如.first/.index等。

6.{$smarty.template}

返回經過處理的當前模板名(不包括目錄)。

7.{$smarty.current_dir}

返回經過處理的當前模板目錄名。

8{$smarty.version}、$smarty.block.child}、{$smarty.block.parent}{$smarty.ldelim}、{$smarty.rdelim}

用的少,不作說明,可以查看手冊瞭解更多內容。

發佈了38 篇原創文章 · 獲贊 14 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章