php學習系列2---smarty模板

一、對模板賦值

將變量輸入到模板

程序:

$this->hello = "Hello world";

模板:

<{$hello}>

輸出:

Hello world

將數組輸入到模板

程序:

$this->color = array('red' => '紅色', 'yellow' => '黃色', 'green' => '綠色');

模板可以使用:

<{$color['red']}>

同時也可以:

<{$color.red>

輸出:

紅色

二、模板內部語法

if,elseif,else 條件判斷

<{if $color == "red"}>

這是紅色的。

<{elseif $color == "green" || $color == "white"}>

這是綠色或者白色的。

<{else}>

這不知道什麼顏色

<{/if}>

Smarty中的if/else除了不使用括號外和PHP的if/else幾乎是一樣的。

include 包含文件

<{include file="header.html"}>

請注意include的包含是以'template_dir'的設置爲根目錄的,而且並不存在相對目錄。所以比如我們的footer.html在"模板目錄/main/footer.html",我們將使用

<{include file="main/footer.html"}>

來進行包含。

在Smarty中還有include_php,和include一樣,只是include_php包含的是可執行的PHP文件。同時,如果使用include_php函數,將可能涉及到Smarty的安全特性,這和{php}語法也是有關的。詳細請參考Smarty中文手冊。

當然,在基於Smarty的模板開發中,我們原則上不建議在模板內使用PHP的功能。

foreach,foreachelse

和PHP的foreach一樣,循環處理數組。

例:$this->color = array('red' => '紅色', 'yellow' => '黃色', 'green' => '綠色');

<{foreach item=colorname from=$color key=enname}>

<{$enname}>: <{$colornam}><br>

<{/foreach}>

將輸出:

red:紅色

yellow:黃色

green:綠色

多維數組也是同樣處理,請留意以下的多維數組:

例:

$students =

   array(

      'name' => 'He Qing',

      'age' => 17,

      'score' => array(

         'math' => 76,

        'english' => 92,

         'PE' => 72

      ),

   ),

   array(

      'name' => 'Lee Wen',

      'age' => 18,

      'score' => array(

         'math' => 69,

        'english' => 80,

         'PE' => 79

      ),

   ),

);

$this->students = $students ;

模板:

學生成績:<br>

<{foreach item=person from=$students}>

姓名:<{$person.name}><br>

年齡:<{$person.age}><br>

分數:

<{foreach item=num key=subject from=$person.score}>

<{$subject}>:<{$num}><br>

<br><br>

<{/foreach}>

<{foreachelse}>

暫無學生數據!

<{/foreach}>

foreachelse是在變量未賦值的時候將顯示。

和foreach差不多的還有section,詳細請參考Smarty中文手冊。

literal

literal主要用於顯示有可能包含大括號等字符信息的 javascript 腳本. 當這些javascript 腳本處於 {literal}{/literal} 標籤中時,模板引擎將不分析它們,而直接顯示。

有時候我們在使用Smarty模板時,會遇到程序正常卻僅輸出空白頁面;這時我們可以檢查一下,是否該模板中包含了javascript腳本。在這些javascript外邊加上literal就不會有問題了。

<{literal}>

<script language=javascript>

  <!--

  function isblank(field) {

  if (field.value == '')

  { return false; }

  else

  {

  document.loginform.submit();

  return true;

  }

  }

  // -->

</script>

<{/literal}>

literal和下面介紹的strip雖然在一般的Smarty教程中很少有介紹,但的確literal和strip對日常的開發是非常有幫助的,尤其是strip。

strip

Smarty將清除{strip} ... {/strip}之間的全部空格以及回車。

建議馬上在您的模板中使用strip標籤,根據實際開發的估計,一般的頁面在使用了strip標籤幾乎可以減少四分之一的html文件大小,尤其在內容特別多的頁面(比如首頁)在網頁的打開速度和顯示速度上面有着明顯的提高。

例子:

{strip}

<table border=0>

<tr>

<td>

<A HREF="{$url}">

<font color="red">This is a test</font>

</A>

</td>

</tr>

</table>

{/strip}

顯示:

<table border=0><tr><td><A HREF="http://my.domain.com">

<font color="red">This is a test</font></A></td></tr></table>

三、SpeedPHP框架在Smarty模板中的函數

在模板中,除了可以使用Smarty本身自帶的函數外,sp框架還提供了一些常用的函數,下面我們裏瞭解一下:

spUrl

和輸出spUrl()函數結果一樣,顯示一個URL地址

比如:

程序中:echo spUrl('article', 'list', array('page'=>3, 'pageSize' => 10)); // 顯示文章列表的第三頁

在模板中使用就是:

<{spUrl c='article' a='list' page=3 pageSize=10}>

T

和輸出 T()函數的結果一樣,顯示多語言情況下的翻譯結果

比如:

程序中:echo T("welcome"); // 顯示在特定語言下的歡迎信息

在模板中則是:

<{T w='welcome'}>

四、HTML相關函數

Smarty提供了一系列的HTML代碼生成函數。以下例子均出自Smarty手冊,詳細說明請參考Smarty中文手冊。

html_checkboxes

生成多個多選框
程序:
$this->cust_checkboxes = array(
            1000 => 'Joe Schmoe',
            1001 => 'Jack Smith',
            1002 => 'Jane Johnson',
            1003 => 'Charlie Brown'
);
$this->customer_id' = 1001;
模板:
<{html_checkboxes name="id" options=$cust_checkboxes checked=$customer_id separator="<br />"}>
輸出:
<label><input type="checkbox" name="checkbox[]" value="1000" />Joe Schmoe</label><br />
<label><input type="checkbox" name="checkbox[]" value="1001" checked="checked" />Jack Smith</label><br />
<label><input type="checkbox" name="checkbox[]" value="1002" />Jane Johnson</label><br />
<label><input type="checkbox" name="checkbox[]" value="1003" />Charlie Brown</label><br />

html_image

生成圖片img標籤,html_image將自動獲取圖片長寬。
模板:
<{html_image file="pumpkin.jpg"}>
輸出:
<img src="pumpkin.jpg" alt="" border="0" width="44" height="68" />

html_options

生成多個下拉框選項組,需要自行加上<select>
程序:
$this->cust_options= array(
            1000 => 'Joe Schmoe',
            1001 => 'Jack Smith',
            1002 => 'Jane Johnson',
            1003 => 'Charlie Brown'
);
$this->customer_id' = 1001;
模板:
<select name=customer_id>
    <{html_options options=$cust_options selected=$customer_id}>
</select>
輸出:
<select name=customer_id>
    <option value="1000">Joe Schmoe</option>
    <option value="1001" selected="selected">Jack Smith</option>
    <option value="1002">Jane Johnson</option>
    <option value="1003">Charlie Brown</option>
</select>

html_radios

生成多個單選框
程序:
$this->cust_radios = array(
            1000 => 'Joe Schmoe',
            1001 => 'Jack Smith',
            1002 => 'Jane Johnson',
            1003 => 'Charlie Brown'
);
$this->customer_id' = 1001;
模板:
<{html_radios name="id" options=$cust_radios checked=$customer_id separator="<br />"}>
輸出:
<input type="radio" name="id[]" value="1000">Joe Schmoe<br />
<input type="radio" name="id[]" value="1001" checked="checked"><br />
<input type="radio" name="id[]" value="1002">Jane Johnson<br />
<input type="radio" name="id[]" value="1003">Charlie Brown<br />

html_select_date

生成年月日下拉框
模板:
{html_select_date month_format="%m" field_order="YMD" start_year="1950" }

html_select_time 生成時分秒下拉框
{html_select_time use_24_hours=true}

html_table

生成一個表格
程序:
$this->data = array(1,2,3,4,5,6,7,8,9);
模板:
{html_table loop=$data cols=4 }
輸出:
<table border="1">
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>5</td><td>6</td><td>7</td><td>8</td></tr>
<tr><td>9</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
</table>

五、對模板變量的修飾

針對輸入到模板的變量,有時候我們需要進行一些轉換修飾,比如對網址進行URL編碼等。下面我們將介紹幾個常用的變量修飾器(Modifiers)

default

默認值
在變量爲空或未賦值的時候,將由默認值替代輸出。
例:<{$user_name|default:'遊客'}>,如果$user_name並未賦值,則輸出“遊客”。

escape

對字符串進行編碼,常用的編碼方式:有html(進行HTML轉碼)url(進行URL轉碼)javascript(javascript轉碼)等
例:$this->url = "http://www.163.com";
模板:<{$url|escape:"url"}>
輸出:http%3A%2F%2Fwww.163.com

lower 小寫 upper 大寫

對字符串進行小寫或大寫的轉換
例:$this->hello = "Hello World!";
模板:
<{$hello|lower}> 
將輸出 hello world!
<{$hello|upper}> 
將輸出 HELLO WORLD!

replace

替換,與str_replace效果相同
例:$this->num = "101010101010101";
模板:<{$num|replace:"1":"0"}>  // 1被替換成了0
輸出:111111111111111

strip_tags

去除HTML標籤,也就是去除<>中間的字符串
例:$this->myword = "<b>hi</b>, <font color=red>this is red font.</font>";
模板:<{$myword|strip_tags}>
輸出:hi,this is red font.

在Smarty手冊中,我們還可以看到一些計算字符串長度和截取字符串的變量修飾器,可是在使用漢字的情況下,目前這些變量修飾器卻不能正常的使用。這個情況我們可以使用sp框架的spAddViewFunction函數功能,將能夠計算漢字的函數和正確截取漢字的函數註冊到模板之中,使得這些函數可以像Smarty內置函數一樣使用。這樣一方面可以令您的應用程序功能更加強大,另一方面也符合了Smarty的設計理念,不破壞模板引擎的功能最小化原則。

當然,上面講述的SpeedPHP框架在Smarty模板中的函數T與spUrl,也都是通過spAddViewFunction方式註冊到模板引擎中的。

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