PHP.22-Smart模版

Smart模版

smarty是一个基于PHP开发的PHP模板引擎。它提供了逻辑与外在内容的分离,简单的讲,目的就是要使PHP程序员同美工分离,使用的程序员改变程序的逻辑内容不会影响到美工的页面设计,美工重新修改页面不会影响到程序的程序逻辑。

美工人员

  1. 写模板, HTML CSS JavaScript

  2. 使用Smarty表现逻辑 放变量, 遍历和判断数据

  PHP程序员

    1. PHP程序和原来一样(连接数据, 图,文件)

    2. 加载Smarty引擎, 并创建对象

    3. 向引擎中分配变量(分数据)

    4. 显示那个模板

Smart中文在线手册

一、基本语法

  定界符建议修改定界符,以防模版中出现内部样式造成混淆

<!--外部样式-->  
        <link rel="stylesheet" type="text/css" href="css/mystyle.css"/>  
        <!--内部样式-->  
        <style type="text/css">  
            p{  
                color: crimson;  
            }  
        </style>  
    </head>  
    <body>  
        
        <!--内联样式-->  
        <a href="http://www.baidu.com"  style="color:blue;" target="_blank">百度:http://www.baidu.com</a>  
三种样式的定义方法

     $tpl->left_delimiter="<{"; //左定界符
     $tpl->right_delimiter="}>"; //右定界符

  注释:在定界符中以两个星号“*”进行注释,如:<{* 注释 *}>

 

二、Smart变量

  1、来自PHP页面中的变量  【调用从PHP分配的变量需在前加"$"符号,调用模板内的assign函数分配的变量也需要加"$"】

index.php:
$smarty = new Smarty;
$smarty->assign('firstname', 'Doug');          //assign:注册函数,将变量注册 $smarty->assign('lastLoginDate', 'January 11th, 2001'); $smarty->display('index.tpl');              //合成模版文件 index.tpl: Hello {$firstname}, glad to see you could make it. Your last login was on {$lastLoginDate}.

    1.1  读取关联数组,需要使用"."符号连接

index.php:
$smarty = new Smarty;
$smarty->assign('Contacts',array('fax' => '555-222-9876','email' => 'zaphod@slartibartfast.com','phone' => array('home' => '555-444-3333','cell' => '555-111-1234')));
$smarty->display('index.tpl'); index.tpl: {$Contacts.fax}<br> {$Contacts.email}<br> {* 打印二维关联数组 *} {$Contacts.phone.home}<br> {$Contacts.phone.cell}<br>

    1.2  读取索引数组

index.php:
$smarty = new Smarty;
$smarty->assign('Contacts',array('555-222-9876','zaphod@slartibartfast.com',array('555-444-3333','555-111-1234')));
$smarty->display('index.tpl');

index.tpl:
<{$Contacts[0]}><br>
<{$Contacts[1]}><br>
{* 二维索引 *}
<{$Contacts[2][0]}><br>
<{$Contacts[2][1]}><br>

    1.3  对象引用

name: <{$person->name}><br>
email: <{$person->email}><br>
View Code

  2、从配置文件读取变量

    要使用 $tpl->configs_dir="configs"    //指定配置文件存放的目录

    在模板.tpl中要使用 <{configs_load file="view.conf"}> 加载view.conf配置文件

    配置文件中的变量需要通过用两个"#"或者是smarty的保留变量 $smarty.config.~来调用

foo.conf:
pageTitle = "This is mine"
bodyBgColor = "#eeeeee"
tableBorderSize = "3"
tableBgColor = "#bbbbbb"
rowBgColor = "#cccccc"

index.tpl:
{config_load file="foo.conf"}
<html>
<title><{#pageTitle#}></title>
<body bgcolor="<{#bodyBgColor#}>">
<table border="<{#tableBorderSize#}>" bgcolor="<{#tableBgColor#}>">
<tr bgcolor="<{#rowBgColor#}>">

index.tpl: ($smarty.config.~)
{config_load file="foo.conf"}
<html>
<title><{$smarty.config.pageTitle}></title>
<body bgcolor="<{$smarty.config.bodyBgColor}>">
<table border="<{$smarty.config.tableBorderSize}>" bgcolor="<{$smarty.config.tableBgColor}>">
<tr bgcolor="<{$smarty.config.rowBgColor}>">

  3、保留变量

    {$smarty}保留变量可以被用于访问一些特殊的模板变量.如:get、post、server、session、cookie、request、now、const、config

    例:get:<{$smarty.get.page}> $_GET  now:<{$smarty.now}> 当前时间戳

三、变量调节器

  变量调节器用于变量,自定义函数和字符串。使用‘|’符号和调节器名称应用调节器。变量调节器由赋予的参数值决定其行为。参数由‘:’符号分开。

index.php:
$smarty = new Smarty;
$smarty->assign('yesterday', strtotime('-1 day'));
$smarty->display('index.tpl');

index.tpl:
{$smarty.now|date_format}
{$smarty.now|date_format:"%A, %B %e, %Y"}
{$smarty.now|date_format:"%H:%M:%S"}
{$yesterday|date_format}
{$yesterday|date_format:"%A, %B %e, %Y"}
{$yesterday|date_format:"%H:%M:%S"}
日期格式
index.php:
$smarty = new Smarty;
$smarty->assign('articleTitle', 'Two Sisters Reunite after Eighteen Years at Checkout Counter.');
$smarty->display('index.tpl');

index.tpl:
{$articleTitle}
{$articleTitle|truncate}
{$articleTitle|truncate:30}
{$articleTitle|truncate:30:""}
{$articleTitle|truncate:30:"---"}
{$articleTitle|truncate:30:"":true}
{$articleTitle|truncate:30:"...":true}

OUTPUT:
Two Sisters Reunite after Eighteen Years at Checkout Counter.
Two Sisters Reunite after Eighteen Years at Checkout Counter.
Two Sisters Reunite after...
Two Sisters Reunite after
Two Sisters Reunite after---
Two Sisters Reunite after Eigh
Two Sisters Reunite after E...
截取指定长度字符truncate

  注:truncate变量可能在截取中英文页面时出现乱码,可通过自定义一个函数,将其注册(register_function/register_block)或定义在插件库modifier.~,来进行调用【如:按utf-8截取的算法】

四、组合修改器分隔多个变量调节器

  对于同一个变量,你可以使用多个修改器。它们将从左到右按照设定好的顺序被依次组合使用。使用时必须要用"|"字符作为它们之间的分隔符。

index.php:
$smarty = new Smarty;
$smarty->assign('articleTitle', 'Smokers are Productive, but Death Cuts Efficiency.');
$smarty->display('index.tpl');

index.tpl:         
{$articleTitle}
{$articleTitle|upper|spacify}
{$articleTitle|lower|spacify|truncate}
{$articleTitle|lower|truncate:30|spacify}
{$articleTitle|lower|spacify|truncate:30:". . ."}
View Code

五、自定义函数

  Smarty 自带的一组自定义函数,用户可根据实际需求进行修改、增加或删除

{counter start=0 skip=2 print=false}

{counter}<br>
{counter}<br>
{counter}<br>
{counter}<br>
counter 用于输出一个记数过程. counter 保存了每次记数时的当前记数值.
{math equation="x + y" x=$height y=$width}

OUTPUT:

9
math 允许模板设计者在模板中进行数学表达式运算.

  用户可根据需求自定函数:

  1、注册函数或块

$smarty->register_function("date_now", "print_current_date");
function print_current_date ($params) { extract($params); if(empty($format)) $format="%b %e, %Y"; return strftime($format,time());}
register_function (string name, mixed impl, bool cacheable, array or null cache_attrs)
$smarty->register_block("translate", "do_translation");
function do_translation ($params, $content, &$smarty, &$repeat) { if (isset($content)) { $lang = $params['lang']; // do some translation with $content return $translation; }}
{* template *}{translate lang="br"} Hello, world!{/translate}
register_block (string name, mixed impl, bool cacheable, array or null cache_attrs)

  2、插件库

    接口规则:命名:以funcition.~开头是函数;以block.~开头是块;以modifier.~过滤函数;

    函数名:function smarty_block_world($args, $content, &$smarty)  function smarty_function_math($params, &$smarty)

        &$smarty:必须加上去,可换名字,但需有这参数引用

六、内建函数

  Smarty自带一些内建函数. 内建函数是模板语言的一部分. 用户不能创建名称和内建函数一样的自定义函数,也不能修改内建函数.

{* 该例在捕获到内容后输出一行包含数据的表格,如果没有捕获到就什么也不输出 *}
{capture name=banner}
{include file="get_banner.tpl"}
{/capture}
{if $smarty.capture.banner ne ""}
    <tr>
        <td>
            {$smarty.capture.banner}
        </td>
    </tr>
{/if}
capture函数的作用是捕获模板输出的数据并将其存储到一个变量里,而不是把它们输出到页面
foreach与PHP的foreach用法相同,关联数组
{if $name eq "Fred"}
    Welcome Sir.
{elseif $name eq "Wilma"}
    Welcome Ma'am.
{else}
    Welcome, whatever you are.
{/if}

{* an example with "or" logic *}
{if $name eq "Fred" or $name eq "Wilma"}
    ...
{/if}

{* same as above *}
{if $name == "Fred" || $name == "Wilma"}
    ...
{/if}

{* the following syntax will NOT work, conditional qualifiers
 must be separated from surrounding elements by spaces *}
{if $name=="Fred" || $name=="Wilma"}
    ...
{/if}


{* parenthesis are allowed *}
{if ( $amount < 0 or $amount > 1000 ) and $volume >= #minVolAmt#}
    ...
{/if}

{* you can also embed php function calls *}
{if count($var) gt 0}
    ...
{/if}

{* test if values are even or odd *}
{if $var is even}
    ...
{/if}
{if $var is odd}
    ...
{/if}
{if $var is not odd}
    ...
{/if}

{* test if var is divisible by 4 *}
{if $var is div by 4}
    ...
{/if}

{* test if var is even, grouped by two. i.e.,
0=even, 1=even, 2=odd, 3=odd, 4=even, 5=even, etc. *}
{if $var is even by 2}
    ...
{/if}

{* 0=even, 1=even, 2=even, 3=odd, 4=odd, 5=odd, etc. *}
{if $var is even by 3}
    ...
{/if}
if 必须于 /if 成对出现. 可以使用 else 和 elseif 子句. 可以使用以下条件修饰词:eq、ne、neq、gt、lt、lte、le、gte、ge、is even、is odd……
 section 用于遍历数组中的数据. section 标签必须成对出现. 必须设置 nameloop 属性. 名称可以是包含字母、数字和下划线的任意组合. 可以嵌套但必须保证嵌套的 name 唯一. 变量 loop (通常是数组)决定循环执行的次数. 当需要在 section 循环内输出变量时,必须在变量后加上中括号包含着的 name 变量.
<table align="center" width="800" border="1">
    <{section loop=$data name="ls" start="10" step="3" max="10"}>
        
        
        <tr>
            <td><{$smarty.section.ls.index}></td>
            <td><{$smarty.section.ls.rownum}></td>
            <td><{$data[ls].id}></td>
            <td><{$data[ls].name}></td>
            <td><{$data[ls].price}></td>
            <td><{$data[ls].num}></td>
            <td><{$data[ls].desn}></td>
            <td><{$data[ls].sub}></td>
            <td>
                <{section loop=$data[ls].sub name="lsin"}>
                    ##<{$data[ls].sub[lsin].one}><br>
                <{/section}>
            </td>
        </tr>
        
    <{sectionelse}>    
        数组中没有数据
    <{/section}>
</table>
section

  注:建议使用section进行数组遍历,因为其效率比foreach更高,而且功能多;但遍历数组时下标必须连续

七、缓存

  Smarty缓存和网页表态化一样, 使用Smarty缓存使用非常方便

    1. 需要开启缓存
    2. 指定一下缓存的时间
    3. 指定缓存文件保存位置

   $tpl->caching=1;                      //开启缓存【在开发阶段不要开,运行阶段再开启】
    $tpl->cache_dir=ROOT."cache";        //缓存文件
    $tpl->cache_lifetime=10;            //缓存文件生存时间

  注意:
    1. 一个模板只能有一个缓存文件,如果一个模板的多个文章,则需要每个文章有一个
  缓存
    $tpl->display("test.tpl", cacheid);

    第二个参数,每变化一个值就会有一个不同的缓存(最好使用$_SERVER["REQUEST_URI"])针对每条URL进行缓存,防止出现重复的缓存文件

    2. 一定要处理,如果有缓存了就不要执行连接数据库和到数据库中操作数据表了。

      使用smarty中的is_cached()方法去判断,它的用法和display()相同   

if(!$tpl->is_cached("test.tpl",$_SERVER["REQUEST_URI"])){
        $mysqli=new mysqli("localhost", "root", "123456", "database");
        $result=$mysqli->query("select id from shops");

  局部缓存设置
    使用一个块标记完成,register_block("nocache", "nocache", false)

function smarty_block_nocache($params, $content, &$s){
        return $content;

test.tpl

  <caption><h1>SHOPS<{nocache}><{$date}><{/nocache}></h1></caption>
        <tr>
  <{nocache}>

    插件库:block.nocache.php,并修改文件Smarty_Compiler.class.php  712行

if (!function_exists($plugin_func)) {
                $message = "plugin function $plugin_func() not found in $plugin_file
";
                $have_function = false;
            } else {
                    if($tag_command=="nocache")
                            $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, false);
                    else
                         $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true);

            }

    清除缓存功能

      $tpl->clear_all_cache();    //清除所有缓存

      clear_cache()    清除指定缓存

Smarty使用注意事项
  1. 因为我们访问是PHP文件,而模板是在PHP中包含的内容,所以在模板中使用 图片,CSS文件,js文件,都要以访问的PHP目录为主

  2. 所有display模板时(还是模板中include),都要以Smarty对象中指定的模板目录为基目录

  3. 如果想让各个目录下的PHP程序都可以加载Smarty和使用Smarty指定的模板和编译目录,唯一的办法就是使用绝对路径。

原文地址:https://www.cnblogs.com/zixuanfy/p/6750591.html