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

数组取值

一维数组
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>.


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

来玩啊
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,277评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,689评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,624评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,356评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,402评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,292评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,135评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,992评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,429评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,636评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,785评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,492评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,092评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,723评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,858评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,891评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,713评论 2 354

推荐阅读更多精彩内容

  • Beetl2.7.16中文文档 Beetl作者:李家智 <xiandafu@126.com> 1. 什么是Beet...
    西漠阅读 2,679评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,654评论 18 139
  • 前言 人生苦多,快来 Kotlin ,快速学习Kotlin! 什么是Kotlin? Kotlin 是种静态类型编程...
    任半生嚣狂阅读 26,208评论 9 118
  • 01 孩子上高三的第二学期,学校为学生要举行一个“成人礼”。其实我的孩子已经过了18岁生日,彼时已经是18岁...
    虹姐有话说阅读 1,190评论 0 0
  • 交织在苍穹中的 阴暗,明亮, 白的和灰的色彩, 欢聚在黑色眼珠中。 耳朵噪杂,刺痛, 震天的乐曲, 掠过空的玻璃。...
    丁驱陋阅读 228评论 1 1