美文网首页PHP首页投稿(暂停使用,暂停投稿)
PHP Day6:黄金搭档Smarty(基础部分)

PHP Day6:黄金搭档Smarty(基础部分)

作者: 王中阳 | 来源:发表于2016-06-24 10:56 被阅读121次

    数组取值

    一维数组
    array (  
       "0" => 'home',  
       '1' => 'who',  
       '2'=> 'tank',  
       '3'=> 'what'  
      );  
    $this->tpl->assign("onearray", $this->onearray);  
    
    • foreach取值:
    {foreach from=$onearray kkey=k item=value }  
     一维key={$k}  一维value={$value}<br />  
    {foreachelse}  
     nothing  
    {/foreach}   
    

    显示的结果是

    一维key=0 一维value=home
    一维key=1 一维value=who
    一维key=2 一维value=tank
    一维key=3 一维value=what
    
    • section取值
    {section name=one loop=$onearray start=0 step=1}  
     index={$smarty.section.one.index},  
     index_prev={$smarty.section.one.index_prev},  
     index_next={$smarty.section.one.index_next},  
     first={$smarty.section.one.first},  
     last={$smarty.section.one.last},  
     iteration ={$smarty.section.one.iteration},  
     total={$smarty.section.one.total},  
     value={$onearray[one]}<br />  
    {sectionelse}  
     nothing  
    {/section} 
    

    显示的结果是

    index=0, index_prev=-1, index_next=1, first=1, last=, iteration =1, total=4, value=home
    index=1, index_prev=0, index_next=2, first=, last=, iteration =2, total=4, value=who
    index=2, index_prev=1, index_next=3, first=, last=, iteration =3, total=4, value=tank
    index=3, index_prev=2, index_next=4, first=, last=1, iteration =4, total=4, value=what
    

    常用函数

    每一个smarty标签都需要用{}或者{% %}括起来,具体用什么形式可以在配置文件中指定。
    但是标签的用法都是一样的。

    {config_load file="colors.conf"}
    
    {include file="header.tpl"}
    
    {if $highlight_name}
        Welcome, <font color="{#fontColor#}">{$name}!</font>    
    {else}
        Welcome, {$name}!
    {/if}
    
    {include file="footer.tpl"}
    
    • 在模板里无论是内建函数还是自定义函数都有相同的语法.
    • 内建函数将在smarty内部工作,例如 {if} , {section} and {strip} .他们不能被修改.
    • 自定义函数通过插件机制起作用,它们是附加函数. 只要你喜欢,可以随意修改.你也可以自行添加.
    • 例如 {html_options} 和 {html_select_date}

    属性

    • 大多数函数都有自己的属性,用以说明或修改他们的行为。
    • smarty中的属性很像html中的属性
    • 静态数值不需要加引号,但是字符串建议加引号
    • 如果变量作为函数的属性,也不能加引号(很好理解,加引号的都作为字符串处理)
    • 属性支持Boolean值(可以是true,on,yes或false,off,no)。
    • 简单来讲,字符串数据加引号,其他类型的数据都不加引号。
    {include file="header.tpl"}
    
    {include file=$includeFile}
    
    {include file=#includeFile#}
    
    {html_select_date display_days=yes}
    
    <SELECT name=company>
    {html_options values=$vals selected=$selected output=$output}
    </SELECT>
    

    双引号里值的嵌入

    • Smarty可以识别嵌入在双引号里面的变量。
    • 只要此变量只包含数字,字母,下划线和中括号[]。
    • 对于其他的符号,变量需要用``括起来。(注意是~这个按键,不是单引号)
    SYNTAX EXAMPLES:
    {func var="test $foo test"} <-- sees $foo
    {func var="test $foo_bar test"} <-- sees $foo_bar
    {func var="test $foo[0] test"} <-- sees $foo[0]
    {func var="test $foo[bar] test"} <-- sees $foo[bar]
    {func var="test $foo.bar test"} <-- sees $foo (not $foo.bar)
    {func var="test `$foo.bar` test"} <-- sees $foo.bar
    
    PRACTICAL EXAMPLES:
    {include file="subdir/$tpl_name.tpl"} <-- will replace $tpl_name with value
    {cycle values="one,two,`$smarty.config.myval`"} <-- must have backticks
    
    • 重点是引入特殊符号时用``括起来

    Smarty的数学运算

    • 就一句话:变量之间可以直接进行数学运算。
    {$foo+1}
    
    {$foo*$bar}
         
    {* some more complicated examples *}
         
    {$foo->bar-$bar[1]*$baz->foo->bar()-3*7}
    
    {if ($foo+$bar.test%$baz*134232+10+$b+10)}
    
    {$foo|truncate:"`$fooTruncCount/$barTruncFactor-1`"}
    
    {assign var="foo" value="`$foo+$bar`"}
    

    Smarty变量

    按照变量的来源分类

    • 从PHP分配的变量
    • 从配置文件读取的变量
      • 通过用两个"#"或者是smarty的保留变量 $smarty.config.来调用
    • {$smarty}保留变量

    • 变量的类型决定了它的前缀是什么符号
    • smarty的变量可以直接输出或者
      • 作为函数属性
      • 修饰符属性
      • 用于内部表达式
    {$Name} 
    
    {$Contacts[row].Phone}
    
    <body bgcolor="{#bgcolor#}">  //#从配置文件中读取变量#
    

    最常用的是从PHP中读数据

    index.php:
    
    
    $smarty = new Smarty;
    $smarty->assign('firstname', 'Doug');
    $smarty->assign('lastLoginDate', 'January 11th, 2001');
    $smarty->display('index.tpl');
    
    index.tpl:
    
    Hello {$firstname}, glad to see you could make it.
    <p>
    Your last login was on {$lastLoginDate}.
    
    OUTPUT:
    
    Hello Doug, glad to see you could make it.
    <p>
    Your last login was on January 11th, 2001.
    

    smarty组合调节器

    对于同一个变量,你可以使用多个修改器。他们会按照从左到右的顺序依次组合使用。使用时必须使用‘|’作为他们之间的分隔符。

    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:". . ."}
    
    
    OUTPUT:
    
    Smokers are Productive, but Death Cuts Efficiency.
    S M O K E R S A R E P R O D U C T I V E , B U T D E A T H C U T S E F F I C I E N C Y .
    s m o k e r s a r e p r o d u c t i v e , b u t d e a t h c u t s...
    s m o k e r s a r e p r o d u c t i v e , b u t . . .
    s m o k e r s a r e p. . .
    

    smarty的内置函数

    • {$var=}:这是{assign}函数的简写版,你可以直接赋值给模版,也可以为数组元素赋值。
    • {idelim}{rdelim}:delim 和 rdelim 用于输出分隔符,也就是大括号 "{" 和 "}". 模板引擎总是尝试解释大括号内的内容,因此如果需要输出大括号,请使用此方法.
    {* this will print literal delimiters out of the template *}
    
    {ldelim}funcname{rdelim} is how functions look in Smarty!
    
    
    OUTPUT:
    
    {funcname} is how functions look in Smarty!
    
    • {call} : 用来调用{function}标签定义的模板函数,类似于插件函数
    • {literal}标签内的数据被当做文本处理,模板忽略其内部的所有字符信息,该特性用于显示有可能包含大括号等字符信息的 javascript 脚本. 当这些信息处于 {literal}{/literal} 标签中时,模板引擎将不分析它们,而直接显示.
    {literal}
        <script language=javascript>
    
        <!--
        function isblank(field) {
        if (field.value == '') 
        { return false; }
        else
        {
        document.loginform.submit();
        return true;
        }
        }
        // -->
    
        </script>
    {/literal}
    
    • section用于循环取值,使用时必须包含name和loop属性,支持嵌套但必须保证嵌套的name唯一。变量loop(通常是数组)决定循环的次数。
    • 当需要在 section 循环内输出变量时,必须在变量后加上中括号包含着的 name 变量. sectionelse 当 loop 变量无值时被执行.
    {* the loop variable only determines the number of times to loop.
     you can access any variable from the template within the section.
     This example assumes that $custid, $name and $address are all
     arrays containing the same number of values *}
    {section name=customer loop=$custid}
        id: {$custid[customer]}<br>
        name: {$name[customer]}<br>
        address: {$address[customer]}<br>
        <p>
    {/section}
    
    
    OUTPUT:
    
    id: 1000<br>
    name: John Smith<br>
    address: 253 N 45th<br>
    <p>
    id: 1001<br>
    name: Jack Jones<br>
    address: 417 Mulberry ln<br>
    <p>
    id: 1002<br>
    name: Jane Munson<br>
    address: 5605 apple st<br>
    <p>
    
    • iteration用于显示循环的次数。注意:iteration 不像index属性受start、step和max属性的影响,该值总是从1开始(index是从0开始的).rownum 是iteration的别名,两者等同.
    • rownum用于显示循环的次数. 该属性是iteration的别名,两者等同.
    {section name=customer loop=$custid}
        {$smarty.section.customer.rownum} id: {$custid[customer]}<br>
        {/section}
    
    
        OUTPUT:
    
        1 id: 1000<br>
        2 id: 1001<br>
        3 id: 1002<br>
    
    • Loop 用于显示该循环上一次循环时的索引值. 该值可以用于循环内部或循环结束后.
    {section name=customer loop=$custid}
    {$smarty.section.customer.index} id: {$custid[customer]}<br>
    {/section}
    
    There were {$smarty.section.customer.loop} customers shown above.
    
    OUTPUT:
    
    0 id: 1000<br>
    1 id: 1001<br>
    2 id: 1002<br>
    
    There were 3 customers shown above.
    
    • total用于显示循环的总次数
        {section name=customer loop=$custid step=2} 
        {$smarty.section.customer.index} id: {$custid[customer]}<br>
        {/section}
    
        There were {$smarty.section.customer.total} customers shown above.
    
        OUTPUT:
    
        0 id: 1000<br>
        2 id: 1001<br>
        4 id: 1002<br>
    
        There were 3 customers shown above.
    

    -{strip}{/strip}去除无用的空格

    {* the following will be all run into one line upon output *}
    {strip}
    <table border=0>
        <tr>
            <td>
                <A HREF="{$url}">
                <font color="red">This is a test</font>
                </A>
            </td>
        </tr>
    </table>
    {/strip}
    
    
    OUTPUT:
    
    <table border=0><tr><td><A HREF="http://my.domain.com"><font color="red">This is a test</font></A></td></tr></table>
    

    注意:

    • 请注意上例,所有行都以HTML标签开头结尾. 所有行被组织到一起运行. 如果在行首和行尾有文本的话,它们也会被组织到一起,就有可能得到你不想得到的结果.

    自定义函数

    • eval:按处理模板的方式计算取得变量的值。该特性用于在配置文件中的标签/变量中嵌入其他模块的标签/变量。
    • 如果指定了 "assign" 这个特殊属性,该函数的输出值将被赋给由 assign 指定的模板变量,而不是直接输出.
    • 技术要点: 待求值处理的变量被当作模板来处理. 它们和模板一样遵循同样的结构和安全特性.
    • 技术要点: 待求值处理的变量每次调用时被重编译,不保存编译版本! 但当打开缓冲设置时,该输出会被其它模板缓冲.
    setup.conf
    ----------
    
    emphstart = <b>
    emphend = </b>
    title = Welcome to {$company}'s home page!
    ErrorCity = You must supply a {#emphstart#}city{#emphend#}.
    ErrorState = You must supply a {#emphstart#}state{#emphend#}.
    
    
    index.tpl
    ---------
    
    {config_load file="setup.conf"}
    
    {eval var=$foo}
    {eval var=#title#}
    {eval var=#ErrorCity#}
    {eval var=#ErrorState# assign="state_error"}
    {$state_error}
    
    OUTPUT:
    
    This is the contents of foo.
    Welcome to Foobar Pub & Grill's home page!
    You must supply a <b>city</b>.
    You must supply a <b>state</b>.
    
    

    一个敲代码,爱分享的人,我在这里!

    来玩啊

    相关文章

      网友评论

      本文标题:PHP Day6:黄金搭档Smarty(基础部分)

      本文链接:https://www.haomeiwen.com/subject/bayodttx.html