zoukankan      html  css  js  c++  java
  • [轉]Smarty模板引擎全教程

    轉自:http://speedphp.com/post/smarty-advanced.html

    Smarty 中文手冊 http://www.hbcms.com/main/smarty/

    Smarty模板引擎全教程

    前面已经介绍了在SpeedPHP框架中使用Smarty模板引擎的方法,下面我们来更详细地介绍Smarty的使用方法。

    本章是对Smarty常用的一些功能进行了详述,让您在最短的时间内掌握Smarty模板的日常开发。如果您需要更深入的了解Smarty这个优秀的PHP模板引擎技术,请参考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>

    <{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"}>  // 将0替换成1
    输出: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方式注册到模板引擎中的。

    在日常开发中,我们将经常需要对输入到模板的变量进行调试,所以可以开启Smarty的调试功能进行调试。详细介绍可以参考

    申明

    非源创博文中的内容均收集自网上,若有侵权之处,请及时联络,我会在第一时间内删除.再次说声抱歉!!!

    博文欢迎转载,但请给出原文连接。

  • 相关阅读:
    Nginx教程(三) Nginx日志管理
    Nginx教程(二) Nginx虚拟主机配置
    官方解析Cookies和Session的区别
    J2EE十三个技术规范
    J2EE十三个规范小结
    tomcat -web.xml里的内容
    tcp协议和udp协议的使用场景
    IntelliJ IDEA创建maven web项目(IDEA新手适用)
    Maven安装与配置
    X86、X64和X86_64区别
  • 原文地址:https://www.cnblogs.com/Athrun/p/1709531.html
Copyright © 2011-2022 走看看