smarty

Smarty是一个php模板引擎。更准确的说,它分开了逻辑程序和外在的内容,提供了一种易于
javascript

管理的方法。能够描述为应用程序员和美工扮演了不一样的角色,由于在大多数状况下,他们不php

多是同一我的。例如,你正在建立一个用于浏览新闻的网页,新闻标题,标签栏,做者和内容等html

都是内容要素,他们并不包含应该怎样去呈现。在Smarty的程序里,这些被忽略了。模板设计java

者们编辑模板,组合使用html标签和模板标签去格式化这些要素的输出(html表格,背景色,字程序员

体大小,样式表,等等)。有一天程序员想要改变文章检索的方式(也就是程序逻辑的改变)。这express

个改变不影响模板设计者,内容仍将准确的输出到模板。一样的,哪天美工吃多了想要彻底重api

作界面,也不会影响到程序逻辑。所以,程序员能够改变逻辑而不须要从新构建模板,模板设计数组

者能够改变模板而不影响到逻辑。缓存

smarty 不尝试将逻辑彻底和模板分开。若是逻辑程序严格的用于页面表现,那么它在模板里less

不会出现问题。有个建议:让应用程序逻辑远离模板,  页面表现逻辑远离应用程序逻辑。这将

在之后使内容更容易管理,程序更容易升级

Smarty的特色之一是"模板编译"。意思是Smarty读取模板文件而后用他们建立php脚本。

这些脚本建立之后将被执行。所以并无花费模板文件的语法解析,同时每一个模板能够享受

到诸如Zend 加速 器(http://www.zend.com)  或者PHP 加速 器

(http://www.php-accelerator.co.uk)。这样的php编译器高速缓存解决方案。

Smaty的一些特色:

•  It is extremely fast.

很是很是的快!

•  It is efficient since the PHP parser does the dirty work.

用 php 分析器干这个苦差事是有效的

•  No template parsing overhead, only compiles once.

不须要多余的模板语法解析,仅仅是编译一次

•  It is smart about recompiling only the template files that have

changed.

仅对修改过的模板文件进行从新编译

•  You can make custom functionsand custom variable modifiers, so the

template language is extremely extensible.

能够编辑'自定义函数'和自定义'变量',所以这种模板语言彻底能够扩展

•  Configurable template delimiter tag syntax, so you can use {}, {{}},

<!--{}-->, etc.

能够自行设置模板定界符,因此你可使用{}, {{}}, <!--{}-->, 等等

•  The if/elseif/else/endif constructs are passed to the PHP parser,

so the {if ...} expression syntax can be as simple or as complex

as you like.

诸如 if/elseif/else/endif 语句能够被传递到 php 语法解析器,因此

{if ...} 表达式是简单的或者是复合的,随你喜欢啦

•  Unlimited nesting of sections, ifs, etc. allowed.

若是容许的话,section 之间能够无限嵌套

•  It is possible to embed PHP code right in your template files,

although this may not be needed (nor recommended) since the engine

is so customizable.

引擎是能够定制的.能够内嵌 php 代码到你的模板文件中,虽然这可能并

不须要(不推荐)

•  Built-in caching support

内建缓存支持

•  Arbitrary template sources

独立模板文件

•  Custom cache handling functions

可自定义缓存处理函数

•  Plugin architecture

插件体系结构

1.  官方网站下载smarty的版本,这里以2.6.18为基础.解压其中的libs,把libs 所有拷贝到

项目中

2.  下面是配置的代码,新建个index.php文件,代码为:

<?php

//配置环境

include_once "libs/Smarty.class.php"; //引入smarty类文件

$smarty = new smarty();//初始化smarry

$smarty->template_dir = "template";// 设置模板目录

$smarty->compile_dir = "template_c"; //设置编译文件目录

$smarty->cache_dir = "cache"; //设置  缓存目录

$smarty->caching = false; //设置缓存开启标志

$smarty->cache_lifetime = "60"; //设置缓存有效时间

$smarty->left_delimiter = '{'; // 设置左分界符号

$smarty->right_delimiter = '}'; // 设置右分界符号

?>

3.在项目目录中分别新建目录template,template_c,cache,

总体目录结构为:

4.方法介绍

assign (name,value)

赋值 用来赋值到模板中。能够指定一对 名称/数值 ,也能够指定包含 名称/数值 的联合数组。

例子:

// 名称/数值 方式

$smarty->assign("Username","raojinpg");

$smarty->assign("Sex",$Sex);

// 联合数组方式

$smarty->assign(array("city" => "jiangxi","state" => "nanchang"));

Fetch (tpl,cache_id,compile_id) 模板,缓存号,编译号

取得输出内容

// 捕获输出

$output = $smarty->fetch("index.tpl");

display (tpl,cache_id,compile_id)  模板,缓存号,编译号

显示

// 显示

$smarty->display("index.tpl");

is_cached (tpl,cache_id)  模板,缓存号

是否被缓存

// 是否已经被缓存

$smarty->caching = true;

If(!$smarty->is_cached("index.tpl")){

$smarty->display("index.tpl");

}

//多缓存模板

$cache_id = sprintf(‘%X’,crc32($cache_id));

If(!$smarty->is_cached("index.tpl",$cache_id)){

$smarty->display("index.tpl",$cache_id);

}

clear_cache (tpl,cache_id,compile_id,inttime) 模板,缓存号,编译号,超出时间

清除某一模板的缓存

//清除某一模板的缓存

$smarty->clear_cache("index.tpl");

//清除多缓存模板

$cache_id = sprintf(‘%X’,crc32($cache_id));

$smarty->clear_cache ("index.tpl",$cache_id)

clear_all_cache (inttime)超出时间

清除全部缓存

//清除全部缓存

$smarty-> clear_all_cache();

修饰符号

equal : 相等、------------------------------------------------ eq

not equal:不等于、-----------------------------------------ne neq

greater than:大于、-----------------------------------------gt

less than:小于、---------------------------------------------lt

less than or equal:小于等于、----------------------------lte ,le

great than or equal:大于等于、---------------------------gte ,ge

is even:是偶数、

is odd:是奇数、

is not even:不是偶数、

is not odd:不是奇数、

not:非、

mod:取余、

div by:被。。。除

==、!=、>、<、<=、>=

变量调节器

* capitalize [首字符大写]

* count_characters [字符计数]

* cat [链接字符串] cat里的值链接到给定的变量后面.

* count_characters[字符计数] {$articleTitle|count_characters:true}决定是否计算空格字符。

* count_sentences[计算句数]

* count_words[计算词数]

* date_format[格式化日期] {$smarty.now|date_format:"%H:%M:%S"}

* default[默认值] {$myTitle|default:"no title"}

* escape[编码] html,htmlall,url,quotes,hex,hexentity,javascript {$articleTitle|escape:"url"}

* indent[缩进] 在每行缩进字符串,默认是4个字符

* lower [小写]

* nl2br [换行符替换成<br />]

* regex_replace [正则替换] {$articleTitle|regex_replace:"/[\r\t\n]/":" "}

* replace [替换]

* spacify [插空]

* string_format [字符串格式化]

* strip [去除(多余空格)]

* strip_tags [去除html标签]

* truncate [截取]

* upper [大写]

* wordwrap [行宽约束]

函数

Capture

capture函数的做用是捕获模板输出的数据并将其存储到一个变量里,而不是把它们输出到页面.

任何在{capture name="name"}和{/capture}之间的数据将被存储到变量$name中,该变量由name属性指定.

在模板中经过$smarty.capture.name 访问该变量.

若是没有指定name 属性,函数默认将使用"default" 做为参数.

{capture}必须成对出现,即以{/capture}做为结尾,该函数不能嵌套使用.

当但愿捕获包含  {insert} 命令的数据时要特别注意.  若是打开了缓存并但愿将 {insert} 命令输出到缓中,

不要捕获该区域的数据

{* 该例在捕获到内容后输出一行包含数据的表格,若是没有捕获到就什么也不输出 *}

{capture name=banner}{include file="get_banner.tpl"}{/capture}

{if $smarty.capture.banner ne ""}{$smarty.capture.banner}{/if}

Config_load

该函数用于从配置文件中加载变量{config_load file="colors.conf"}  使用{#变量#}

配置文件内容

配置文件内容

# global variables

pageTitle = "Main Menu"

bodyBgColor = #000000

tableBgColor = #000000

rowBgColor = #00ff00

[Customer]

pageTitle = "Customer Info"

[Login]

pageTitle = "Login"

focus = "username"

Intro = """This is a value that spans more

than one line. you must enclose

it in triple quotes."""

# hidden section

[.Database]

host=my.domain.com

db=ADDRESSBOOK

user=php-user

pass=foobar

///////////////////////////////////////////////模板文件内容

{config_load file="colors.conf"}

<html>

<title>{#pageTitle#}</title>

<body bgcolor="{#bodyBgColor#}">

<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">

<tr bgcolor="{#rowBgColor#}">

<td>First</td>

<td>Last</td>

<td>Address</td>

</tr>

</table>

</body>

</html>

带section 属性的config_load 函数演示

{config_load file="colors.conf" section="Customer"}

<html>

<title>{#pageTitle#}</title>

<body bgcolor="{#bodyBgColor#}">

<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">

<tr bgcolor="{#rowBgColor#}">

<td>First</td>

<td>Last</td>

<td>Address</td>

</tr>

</table>

</body>

</html>

PHP

容许模板使用PHP语法

{php}

echo time();

{/php}

Literal

标签区域内的数据将被看成文本处理,此时模板将忽略其内部的全部字符信息.  该特性用于显示有可能包

含大括号等字符信息的javascript 脚本

{literal}

<script>

function fun(){

alert(1);

}

</script>

{/literal}

include

Include 标签用于在当前模板中包含其它模板.  当前模板中的变量在被包含的模板中可用.  必须指定file

属性,该属性指明模板资源的位置.

{include file="header.tpl"}

//能够带参数,

{include file="header.tpl" title="标题"}

Insert

所包含的内容不会被缓存,每次调用该模板都会从新执行该函数.

//php 代码

<?php

Function insert_nocache($array){

//Return time();

Print_r($array);

}

?>

//模板代码

{insert name="nocache" tid="2"}

ldelim,rdelim

ldelim 和rdelim 用于输出分隔符,也就是大括号"{" 和"}". 模板引擎老是尝试解释大括号内的内容,因

此若是须要输出大括号,请使用此方法

if,elseif,else

if 必须于/if 成对出现. 可使用else 和elseif 子句

{if $name eq "Fred"}

Welcome Sir.

{elseif $name eq "Wilma"}

Welcome Ma'am.

{else}

Welcome, whatever you are.

{/if}

foreach,foreachelse

foreach 是除section 以外处理循环的另外一种方案(根据不一样须要选择不一样的方案).

foreach 用于处理简单数组(数组中的元素的类型一致),它的格式比section 简单许多,缺点是只能处理简

单数组.

foreach 必须和/foreach 成对使用,且必须指定from 和item 属性.

name 属性能够任意指定(字母、数字和下划线的组合).

foreach 能够嵌套,但必须保证嵌套中的foreach 名称惟一.

from 属性(一般是数组)决定循环的次数.

foreachelse 语句在from 变量没有值的时候被执行.

{* 该例将输出数组 $custid 中的全部元素的值 *}

//php 代码

$smarty->assign('custid',range(1,3));

//tpl

{foreach from=$custid item=curr_id}

id: {$curr_id}<br>

{/foreach}

OUTPUT:

id: 1<br>

id: 2<br>

id: 3<br>.

{*多惟*}

//php 代码

$smarty->assign("contacts",

array(array("phone" => "1", "fax" => "2", "cell" => "3"),

array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")));

{* 键就是数组的下标,请参看关于数组的解释 *}

//tpl

{foreach name=outer item=contact from=$contacts}

{foreach key=key item=item from=$contact}

{$key}: {$item}<br>

{/foreach}

{/foreach}

OUTPUT:

phone: 1<br>

fax: 2<br>

cell: 3<br>

phone: 555-4444<br>

fax: 555-3333<br>

cell: 760-1234<br>

section,sectionelse

section 用于遍历数组中的数据.  section  标签必须成对出现.  必须设置  name  和  loop 属性.  名称能够是包

含字母、数字和下划线的任意组合.  能够嵌套但必须保证嵌套的name 惟一.  变量loop (一般是数组)决定

循环执行的次数.  当须要在section 循环内输出变量时,必须在变量后加上中括号包含着的name 变量.

sectionelse 当loop 变量无值时被执行

index:用于显示当前循环的索引,从0开始(若是指定了start属性,那么由该值开始),每次加1(若是指定了

step属性,那么由该值决定).若是没有指定step和start属性,此值的做用和iteration相似,只不过从0开始

而已.

index_prev:用于显示上一个循环索引值. 循环开始时,此值为-1.

index_next:用于显示下一个循环索引值.  循环执行到最后一次时,此值仍然比当前索引值大1(若是指定了

step,取决于此值).

iteration:用于显示循环的次数.iteration 不像index属性受start、step和max属性的影响,该值老是从1开始

(index是从0开始的).rownum 是iteration的别名,二者等同.

first:若是当前循环第一次执行,first 被设置为true.

last:若是当前循环执行到最后一次,last 被设置为true.

rownum:用于显示循环的次数. 该属性是iteration的别名,二者等同.

loop:用于显示该循环上一次循环时的索引值. 该值能够用于循环内部或循环结束后.

show:是section 的参数. show 取值为布尔值true 或false. 若是设置为false,该循环将不显示. 若是指定

了sectionelse 子句,该字句是否显示也取决于该值.

total:用于显示循环执行总的次数. 能够在循环中或执行结束后调用此属性.

//一维

{section name=item loop=$array2}

值为:{$array2[item]}

{$item}

{/section}

//一维

{section name=n loop=$people}

name:{$people[n]}<br/>

{/section}

//关联数组

{section name=sn loop=$news}

{if $smarty.section.sn.first}

<table>

<th>id</th>

<th>title</th>

{/if}

<tr>

<td>{$news[sn].id}</td>

<td>{$news[sn].title}</td>

</tr>

{if $smarty.section.sn.last}

</table>

{/if}

{sectionelse}

there is no news.

{/section}

strip

Smarty 在显示前将除区任何位于{strip}{/strip} 标记中数据的首尾空格和回车.  这样能够保证模板容易理

解且不用担忧多余的空格致使问题

扩展方法

在smarty中带了比较多的内部方法,若是咱们要扩展一个capitalize相似的方法那如何作呢

假定咱们的方法为checkemail

首先创建个文件,名称为modifier. checkemail.php

而后代码为

<?php

Function smarty_checkemail($string){

//这里作你本身须要处理的事情

}

?>

相关文章
相关标签/搜索