Smarty - the compiling PHP template engine

Monte Ohrt <monte@ispi.net>
Andrei Zmievski <andrei@php.net>

Copyright © 2001, 2002, 2003 by ispi of Lincoln, Inc.

Table of Contents [内容列表]
Preface [序]
I. Getting Started [开始]
1. What is Smarty? [什么是Smaty?]
2. Installation [安装]
Requirements [安装]
Basic Installation [基本安装]
Extended Setup [扩展设置]
II. Smarty For Template Designers [模板设计者篇]
3. Basic Syntax [基本语法]
Comments [注释]
Functions [函数]
Attributes [属性]
Embedding Vars in Double Quotes [双引号里值的嵌入]
Math [数学运算]
4. Variables [变量]
Variables assigned from PHP [从PHP分配的变量]
Variables loaded from config files [从配置文件读取的变量]
{$smarty} reserved variable [{$smarty}保留变量]
5. Variable Modifiers [变量调节器]
capitalize [首字符大写]
count_characters [字符计数]
cat [连接字符串]
count_paragraphs [计算段数]
count_sentences [计算句数]
count_words [计算词数]
date_format [格式化日期]
default [默认值]
escape [编码]
indent [缩进]
lower [小写]
nl2br [换行符替换成 <br />]
regex_replace [正则替换]
replace [替换]
spacify [插空]
string_format [字符串格式化]
strip [去除(多余空格)]
strip_tags [去除html标签]
truncate [截取]
upper [大写]
wordwrap [行宽约束]
6. Combining Modifiers [组合修改器]
7. Built-in Functions [内建函数]
capture
config_load
foreach,foreachelse
include
include_php
insert
if,elseif,else
ldelim,rdelim
literal
php
section,sectionelse
strip
8. Custom Functions [自定义函数]
assign
counter
cycle
debug
eval
fetch
html_checkboxes
html_image
html_options
html_radios
html_select_date
html_select_time
html_table
math
mailto
popup_init
popup
textformat
9. Config Files [配置文件]
10. Debugging Console [调试控制台]
III. Smarty For Programmers [程序员篇]
11. Constants [常量]
SMARTY_DIR [Smarty目录]
12. Variables [变量]
$template_dir [模板目录变量]
$compile_dir [编译目录变量]
$config_dir [配置目录变量]
$plugins_dir [插件目录变量]
$debugging [调试变量]
$debug_tpl [调试模板]
$debugging_ctrl [调试控制变量]
$global_assign [全局配置变量]
$undefined [未定义变量]
$autoload_filters [自动加载过滤器变量]
$compile_check [编译检查变量]
$force_compile [强迫编译变量]
$caching [缓存变量]
$cache_dir [缓存目录变量]
$cache_lifetime [缓存生存时间变量]
$cache_handler_func [缓存处理函数变量]
$cache_modified_check [缓存修改检查变量]
$config_overwrite [配置覆盖变量]
$config_booleanize [配置布尔化变量]
$config_read_hidden [配置读取隐藏变量]
$config_fix_newlines [配置固定换行符变量]
$default_template_handler_func [默认模板处理函数变量]
$php_handling [php处理变量]
$security [安全变量]
$secure_dir [安全目录变量]
$security_settings [安全配置变量]
$trusted_dir [信任目录变量]
$left_delimiter [左结束符变量]
$right_delimiter [右结束符变量]
$compiler_class [编译类变量]
$request_vars_order [变量顺序变量]
$request_use_auto_globals [自动全局变量]
$compile_id [编译id变量]
$use_sub_dirs [子目录变量]
$default_modifiers [默认修正器变量]
$default_resource_type [默认源类型变量]
13. Methods [方法]
append [添加]
append_by_ref [引用添加]
assign [赋值]
assign_by_ref [引用赋值]
clear_all_assign [清除所有赋值]
clear_all_cache [清除所有缓存]
clear_assign [清除赋值]
clear_cache [清除缓存]
clear_compiled_tpl [清除已编译模板]
clear_config [清除配置]
config_load [加载配置]
display [显示]
fetch [取得输出的内容]
get_config_vars [取配置变量的值]
get_registered_object [取得已注册的对象]
get_template_vars [取得模板变量的值]
is_cached [是否已被缓存]
load_filter [加载过滤器]
register_block [注册一个块]
register_compiler_function [注册编译函数]
register_function [注册函数]
register_modifier [注册修饰器]
register_object [注册对象]
register_outputfilter [注册输出过滤器]
register_postfilter [注册提交过滤器]
register_prefilter [注册预过滤器]
register_resource [注册资源]
trigger_error [触发错误]
template_exists [模板是否存在]
unregister_block [注销一个块]
unregister_compiler_function [注销编译函数]
unregister_function [注销函数]
unregister_modifier [注销修饰器]
unregister_object [注销对象]
unregister_outputfilter [注销输出过滤器]
unregister_postfilter [注销提交过滤器]
unregister_prefilter [注销预过滤器]
unregister_resource [注销资源]
14. Caching [缓存]
Setting Up Caching [建立缓存]
Multiple Caches Per Page [每页多个缓存]
Cache Groups [缓存集合]
Controlling Cacheability of Plugins' Output [控制插件输出的缓冲能力]
15. Advanced Features [高级特点]
Objects [对象]
Prefilters [预过滤器]
Postfilters [后过滤器]
Output Filters [输出滤镜]
Cache Handler Function [缓冲处理函数]
Resources [资源]
16. Extending Smarty With Plugins [以插件扩展Smarty]
How Plugins Work [插件如何工作]
Naming Conventions [命名约定]
Writing Plugins [编写插件]
Template Functions [模板函数]
Modifiers [修正器]
Block Functions [块函数]
Compiler Functions [编译函数]
Prefilters/Postfilters [预滤器/后滤器]
Output Filters [输出过滤器]
Resources [资源]
Inserts [插入]
IV. Appendixes [附录]
17. Troubleshooting [疑难解答]
Smarty/PHP errors [Smarty/PHP 错误]
18. Tips & Tricks [使用技巧和经验]
Blank Variable Handling [空白变量处理]
Default Variable Handling [默认变量处理]
Passing variable title to header template [传递变量标题给头模板]
Dates [日期]
WAP/WML
Componentized Templates [组合的模板]
Obfuscating E-mail Addresses [拒绝电子邮件地址]
19. Resources [相关资源]
20. BUGS [漏洞]
21. LIST 翻译人员列表
Next
Preface


Preface

Smarty - PHP 模板编译引擎
Priv Next

Preface[序]

It is undoubtedly one of the most asked questions on the PHP mailing lists: how do I make my PHP scripts independent of the layout? While PHP is billed as "HTML embedded scripting language", after writing a couple of projects that mixed PHP and HTML freely one comes up with the idea that separation of form and content is a Good Thing [TM]. In addition, in many companies the roles of layout designer and programmer are separate. Consequently, the search for a templating solution ensues.

该如何使我的PHP脚本从设计中独立出来？这无疑地是在 PHP 邮件列表上所提问的最多的问题之一。虽然 PHP 被标榜为 "HTML 嵌入式语言"， 在写过许多php和html混合式的工程之后，我产生了一个分离表单和内容的想法。而且，在许多公司里规划设计者的角色和程序设计者是分开的。于是,这样的一个模板解决方案产生了........

In our company for example, the development of an application goes on as follows: After the requirements docs are done, the interface designer makes mockups of the interface and gives them to the programmer. The programmer implements business logic in PHP and uses interface mockups to create skeleton templates. The project is then handed off to the HTML designer/web page layout person who brings the templates up to their full glory. The project may go back and forth between programming/HTML a couple of times. Thus, it's important to have good template support because programmers don't want anything to do with HTML and don't want HTML designers mucking around with PHP code. Designers need support for config files, dynamic blocks and other interface issues, but they don't want to have to deal with intricacies of the PHP programming language.

例如在我们公司,一个应用程序的开发流程如下：在提交计划文档之后,界面设计者[美工]制作了网站的外观模型,然后把它交给后台程序员。程序员使用PHP实现商业逻辑,同时使用外观模型做成基本架构。然后工程被返回到html页面设计者继续完善。就这样工程可能在后台程序员和页面设计者之间来来回回好几次。由于后台程序员不喜欢干预任何有关html标签，同时也不需要美工们和php鬼混在一起；美工设计者只需要配置文件，动态区块和其他的界面部分，不必要去接触那些错综复杂的php代码 。因此，这时候有一个很好的模板支持就显得很重要了。
Looking at many templating solutions available for PHP today, most of them provide a rudimentary way of substituting variables into templates and do a limited form of dynamic block functionality. But our needs required a bit more than that. We didn't want programmers to be dealing with HTML layout at ALL, but this was almost inevitable. For instance, if a designer wanted background colors to alternate on dynamic blocks, this had to be worked out with the programmer in advance. We also needed designers to be able to use their own configuration files, and pull variables from them into the templates. The list goes on.

纵观现今存在的许多php模板解决方案,大多数都只是提供了用模板取代变量和将动态区块的功能有限的格式化的基本方法。但是我们的需求比这个要高的多。我们完全不想要php程序员去设计html页面，可是这又是不可避免的。例如:如果美工想要在动态区块之间交替不同的背景颜色，他就可能得和程序员预先说好。同样,美工们也应该有自己对于页面设计的配置文件，这同样可以通过变量把他们拉到模板里边去。继续。

We started out writing out a spec for a template engine back in late 1999. After finishing the spec, we began to work on a template engine written in C that would hopefully be accepted for inclusion with PHP. Not only did we run into many complicated technical barriers, but there was also much heated debate about exactly what a template engine should and should not do. From this experience, we decided that the template engine should be written in PHP as a class, for anyone to use as they see fit. So we wrote an engine that did just that and SmartTemplate came into existence (note: this class was never submitted to the public). It was a class that did almost everything we wanted: regular variable substitution, supported including other templates, integration with config files, embedding PHP code, limited 'if' statement functionality and much more robust dynamic blocks which could be multiply nested. It did all this with regular expressions and the code turned out to be rather, shall we say, impenetrable. It was also noticably slow in large applications from all the parsing and regular expression work it had to do on each invocation. The biggest problem from a programmer's point of view was all the necessary work in the PHP script to setup and process templates and dynamic blocks. How do we make this easier?

早在1999年后期,我们就已经开始为模板引擎写说明文档。在完成这个文档之后,我们开始用c写一个模板引擎，并有希望被包含到php里去。在 撞上了许多的技术难题的同时，“什么是模板应该做的,什么不该做”这个问题，也被热烈的讨论着。从这些经验，我们决定应该用Php将模板引擎写成一个类，让任何觉得合适的人使用它。所以我们写了一个引擎，从此就有了smarty.(注:这个类以前从来没有公开发表过)。这个类几乎达到了我们所有的要求：常规变量替换，支持包括其他模板，使用配置文件集成设置，嵌入Php代码，限制'if'语句的作用，还有更多的可以多层嵌套的健壮的动态区块。它用常规表达式做到这一切，于是代码变得相当，我们可以说：令人费解的。在每次调用的时候，都要去解析 那些语法和常规表达式，于是在大型应用的时候，它显然慢了下来。在程序员的眼光看来，最大的问题还是使用php脚本建立和处理模板和动态区块的所有必要工作。我们应该如何使他变得更简单？

Then came the vision of what ultimately became Smarty. We know how fast PHP code is without the overhead of template parsing. We also know how meticulous and overbearing the PHP language may look to the average designer, and this could be masked with a much simpler templating syntax. So what if we combined the two strengths? Thus, Smarty was born...

我们可以想象smarty应该有怎样的最后表现。我们知道php代码如果没有了模板解析的开销将有多快，我们也知道从一般的美工看来php语言是多么的"恐怖"，然而这一切可以被一种更简单的模板语法掩饰掉。我们应该怎样把这两种方法的长处结合起来？
于是，Smarty诞生了......

Prev Home Next
Smarty - the compiling PHP template engine
[Smarty - PHP 模板编译引擎]
Getting Started

Getting Started[开始]


Getting Started

Prev Next

I. Getting Started 开始

Table of Contents
1. What is Smarty? 什么是smaty?
2. Installation 安装
Prev | Home | Next
Preface 序 |  | What is Smarty? 什么是Smarty？


What is Smarty?

Prev Next

Chapter 1. What is Smarty?

第一章.什么是Smaty?

Smarty is a template engine for PHP. More specifically, it facilitates a manageable way to separate application logic and content from its presentation. This is best described in a situation where the application programmer and the template designer play different roles, or in most cases are not the same person. For example, let's say you are creating a web page that is displaying a newspaper article. The article headline, tagline, author and body are content elements, they contain no information about how they will be presented. They are passed into Smarty by the application, then the template designer edits the templates and uses a combination of HTML tags and template tags to format the presentation of these elements (HTML tables, background colors, font sizes, style sheets, etc.) One day the programmer needs to change the way the article content is retrieved (a change in application logic.) This change does not affect the template designer, the content will still arrive in the template exactly the same. Likewise, if the template designer wants to completely redesign the templates, this requires no changes to the application logic. Therefore, the programmer can make changes to the application logic without the need to restructure templates, and the template designer can make changes to templates without breaking application logic.

Smarty是一个php模板引擎。更准确的说,它分开了逻辑程序和外在的内容,提供了一种易于管理的方法。可以描述为应用程序员和美工扮演了不同的角色,因为在大多数情况下 ,他们不可能是同一个人。例如,你正在创建一个用于浏览新闻的网页,新闻标题,标签栏,作者和内容等都是内容要素,他们并不包含应该怎样去呈现。在Smarty的程序里,这些被忽略了。模板设计者们编辑模板,组合使用html标签和模板标签去格式化这些要素的输出(html表格,背景色,字体大小,样式表,等等)。有一天程序员想要改变文章检索的方式(也就是程序逻辑的改变)。这个改变不影响模板设计者,内容仍将准确的输出到模板。同样的,哪天美工吃多了想要完全重做界面,也不会影响到程序逻辑。因此,程序员可以改变逻辑而不需要重新构建模板,模板设计者可以改变模板而不影响到逻辑。

Now for a short word on what Smarty does NOT do. Smarty does not attempt to completely separate logic from the templates. There is no problem with logic in your templates under the condition that this logic is strictly for presentation. A word of advice: keep application logic out of the templates, and presentation logic out of the application. This will most definately keep things manageable and scalable for the foreseeable future.

现在简短的说一下什么是smarty不做的。smarty不尝试将逻辑完全和模板分开。如果逻辑程序严格的用于页面表现,那么它在模板里不会出现问题。有个建议:让应用程序逻辑远离模板, 页面表现逻辑远离应用程序逻辑。这将在以后使内容更容易管理,程序更容易升级。

One of the unique aspects about Smarty is the template compling. This means Smarty reads the template files and creates PHP scripts from them. Once they are created, they are executed from then on. Therefore there is no costly template file parsing for each request, and each template can take full advantage of PHP compiler cache solutions such as Zend Accelerator (http://www.zend.com) or PHP Accelerator (http://www.php-accelerator.co.uk).

Smarty的特点之一是"模板编译"。意思是Smarty读取模板文件然后用他们创建php脚本。这些脚本创建以后将被执行。因此并没有花费模板文件的语法解析,同时每个模板可以享受到诸如Zend加速器(http://www.zend.com) 或者PHP加速器(http://www.php-accelerator.co.uk)。这样的php编译器高速缓存解决方案。

Some of Smarty's features:

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 functions and 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
    插件体系结构

Prev | Home | Next
Getting Started [开始] | Up | Installation [安装]


Installation

Prev Next

Chapter 2. Installation
第二章. 安装

Table of Contents
Requirements要求
Basic Installation基本安装
Extended Setup扩展设置

Requirements 要求

Smarty requires a web server running PHP 4.0.6 or later.
Smarty要求web服务器运行php4.0.6和以上版本.

Prev | Home | Next
What is Smarty? 什么是Smarty？ | Up | Basic Installation 基本安装


Basic Installation

Prev

Chapter 2. Installation
第二章.安装

 Next

Basic Installation 基本安装

Install the Smarty library files which are in the /libs/ directory of the distribution. These are the PHP files that you SHOULD NOT edit. They are shared among all applications and they only get updated when you upgrade to a new version of Smarty.
安装Smarty发行版在/libs/目录里的库文件(就是解压了). 这些php文件你可不能乱画哦.这些文件被所有应用程序共享,也只能在你升级到新版的smarty的时候得到更新。

Example 2-1. Smarty library files
例 2-1.Smarty库文件

Smarty.class.php
Smarty_Compiler.class.php
Config_File.class.php
debug.tpl
/core/*.php (all of them)
/plugins/*.php (all of them)

Smarty uses a PHP constant named SMARTY_DIR which is the system filepath Smarty library directory. Basically, if your application can find the Smarty.class.php file, you do not need to set SMARTY_DIR, Smarty will figure it out on its own. Therefore, if Smarty.class.php is not in your include_path, or you do not supply an absolute path to it in your application, then you must define SMARTY_DIR manually. SMARTY_DIR must include a trailing slash.
Smarty使用一个叫做'SMARTY_DIR'的php常量作为它的系统库目录。基本上,如果你的应用程序可以找到 Smarty.class.php文件,你不需要设置SMARTY_DIR,Smarty将会自己运作。但是,如果 Smarty.class.php没有在你的include_path(php.ini里的一项设置)里,或者没有在你的应用程序里设置它的绝对路径的时候,你就必须手动配置SMARTY_DIR 了(大多数程序都如此)SMARTY_DIR必须包含结尾斜杠。

Here is how you create an instance of Smarty in your PHP scripts:
这里是你在你的php脚本里创建一个smarty的应用实例的例子:

Example 2-2. Create Smarty instance of Smarty
例 2-2.创建Smarty实例

require('Smarty.class.php');
$smarty = new Smarty;

Try running the above script. If you get an error saying the Smarty.class.php file could not be found, you have to do one of the following:
试着运行一下以上脚本,如果你发现"未找到Smarty.class.php 文件"的错误时,你应该这样做:

Example 2-3. Supply absolute path to library file
例 2-3.加入库文件目录的绝对路径

require('/usr/local/lib/php/Smarty/Smarty.class.php');
$smarty = new Smarty;

Example 2-4. Add library directory to php_include path
例 2-4.在include_path加入库文件目录

// Edit your php.ini file, add the Smarty library
// directory to the include_path and restart web server.
// Then the following should work:
require('Smarty.class.php');
$smarty = new Smarty;

Example 2-5. Set SMARTY_DIR constant manually
例 2-5.手工设置SMARTY_DIR常量

define('SMARTY_DIR','/usr/local/lib/php/Smarty/');
require(SMARTY_DIR.'Smarty.class.php');
$smarty = new Smarty;

Now that the library files are in place, it's time to setup the Smarty directories for your application. Smarty requires four directories which are (by default) named templates , templates_c , configs and cache . Each of these are definable by the Smarty class properties $template_dir , $compile_dir , $config_dir , and $cache_dir respectively. It is highly recommended that you setup a separate set of these directories for each application that will use Smarty.
现在库文件已经搞定,该是设置为你的应用程序配置其他有关Smarty的目录的时候了。Smarty要求4个目录,默认下命名为:tempalates, templates_c, configs and cache。每个都是可以自定义的,可以修改Smarty类属性: $template_dir, $compile_dir, $config_dir, and $cache_dir respectively。强烈推荐你为每个用到smarty的应用程序设置单一的目录!

Be sure you know the location of your web server document root. In our example, the document root is "/web/www.mydomain.com/docs/". The Smarty directories are only accessed by the Smarty library and never accessed directly by the web browser. Therefore to avoid any security concerns, it is recommended to place these directories outside of the document root.
确定你已经知道了你的web服务器文件根目录。在我们的例子里,文件根目录是:"/web/www.mydomain.com/docs/"Smarty的4个目录 只可以被那些库文件访问,不可以被网络上的浏览器访问的目录。因此为避免任何安全问题,要求将那4个目录和网页文件目录(就是浏览器看的)分开来。

For our installation example, we will be setting up the Smarty environment for a guest book application. We picked an application only for the purpose of a directory naming convention. You can use the same environment for any application, just replace "guestbook" with the name of your app. We'll place our Smarty directories under "/web/www.mydomain.com/smarty/guestbook/".
在我们的安装例子里,我们将为一个留言板程序配置smarty环境。我们挑选应用程序只为了实现目录命名约定。你可以对任何程序使用相同的环境,只要将"guestbook"改成你要的名字就可以了。我们将把Smarty目录放在 "/web/www.mydomain.com/smarty/guestbook/"下。

You will need as least one file under your document root, and that is the script accessed by the web browser. We will call our script "index.php", and place it in a subdirectory under the document root called "/guestbook/".
在你的文档目录下至少得有一个文件,这个文件可以被浏览器访问.我们叫它 "index.php"好了.把它放到"/guestbook/"目录下.

Technical Note: It is convenient to setup the web server so that "index.php" can be identified as the default directory index, so if you access "http://www.mydomain.com/guestbook/", the index.php script will be executed without "index.php" in the URL. In Apache you can set this up by adding "index.php" onto the end of your DirectoryIndex setting (separate each entry with a space.)
技术提示：建立web服务器很方便，这个文件可以被web服务器自动识别。如果你访问"http://www.mydomain.com/guestbook/"，你不需要在URL上输入"index.php"，index.php脚本就可以被执行。在Apache服务器中，可以通过在DirectoryIndex的后面添加"index.php" 文件（用反斜杠分开每个入口）来完成设置。

Lets take a look at the file structure so far:
现在我们看看这些文件结构:

Example 2-6. Example file structure
例 2-6.例子的文件结构

/usr/local/lib/php/Smarty/Smarty.class.php
/usr/local/lib/php/Smarty/Smarty_Compiler.class.php
/usr/local/lib/php/Smarty/Config_File.class.php
/usr/local/lib/php/Smarty/debug.tpl
/usr/local/lib/php/Smarty/core/*.php
/usr/local/lib/php/Smarty/plugins/*.php

/web/www.mydomain.com/smarty/guestbook/templates/
/web/www.mydomain.com/smarty/guestbook/templates_c/
/web/www.mydomain.com/smarty/guestbook/configs/
/web/www.mydomain.com/smarty/guestbook/cache/

/web/www.mydomain.com/docs/guestbook/index.php

Smarty will need write access to the $compile_dir and $cache_dir , so be sure the web server user can write to them. This is usually user "nobody" and group "nobody". For OS X users, the default is user "www" and group "www". If you are using Apache, you can look in your httpd.conf file (usually in "/usr/local/apache/conf/") to see what user and group are being used.

Smarty的 $compile_dir 和$cache_dir必须可写。通常是user "nobody" 和 group "nobody"。如果是 OSX用户,默认为user "web" 和 group "web"。如果你在使用Apache,你可以看看httpd.conf 文件 (通常在"/usr/local/apache/conf/"目录下)哪些user和group正在被使用。

Example 2-7. Setting file permissions
例 2-7 文件权限设置

chown nobody:nobody /web/www.mydomain.com/smarty/guestbook/templates_c/
chmod 770 /web/www.mydomain.com/smarty/guestbook/templates_c/

chown nobody:nobody /web/www.mydomain.com/smarty/guestbook/cache/
chmod 770 /web/www.mydomain.com/smarty/guestbook/cache/

Technical Note: chmod 770 will be fairly tight security, it only allows user "nobody" and group "nobody" read/write access to the directories. If you would like to open up read access to anyone (mostly for your own convenience of viewing these files), you can use 775 instead.

技术提示:
chmod 770相当安全了,它只让user "nobody" 和 group "nobody" 读/写 访问。如果你要对任何人开放读取访问权限(大多是为了你自己查看文件),你可以使用 775。

We need to create the index.tpl file that Smarty will load. This will be located in your $template_dir.
我们需要创建index.tpl文件让smarty载入.这个文件放在 $template_dir目录里。

Example 2-8. Editing /web/www.mydomain.com/smarty/guestbook/templates/index.tpl
例 2-8 编辑/web/www.mydomain.com/smarty/templates/index.tpl

{* Smarty *}

Hello, {$name}!

Technical Note: {* Smarty *} is a template comment. It is not required, but it is good practice to start all your template files with this comment. It makes the file easy to recognize regardless of the file extension. For example, text editors could recognize the file and turn on special syntax highlighting.

技术提示:
{* Smarty *} 是一个模板注释。虽然并不是必须的,但是这可以很好的锻炼你在模板文件里加入注释的习惯。它可以使文件便于识别。例如，一些文本编辑器可以识别这个文件,并加以语法高亮显示。

Now lets edit index.php. We'll create an instance of Smarty, assign a template variable and display the index.tpl file. In our example environment, "/usr/local/lib/php/Smarty" is in our include_path. Be sure you do the same, or use absolute paths.

现在来编辑index.php。我们将创建一个Smarty的实例,指派模板变量,显示 index.tpl文件。在我们的例子的环境里, "/usr/local/lib/php/Smarty"已经包括在了 include_path里了。

Example 2-9. Editing /web/www.mydomain.com/docs/guestbook/index.php
例 2-9.编辑/web/www.mydomain.com/docs/guestbook/index.php

// load Smarty library
require('Smarty.class.php');

$smarty = new Smarty;

$smarty->template_dir = '/web/www.mydomain.com/smarty/guestbook/templates/';
$smarty->compile_dir = '/web/www.mydomain.com/smarty/guestbook/templates_c/';
$smarty->config_dir = '/web/www.mydomain.com/smarty/guestbook/configs/';
$smarty->cache_dir = '/web/www.mydomain.com/smarty/guestbook/cache/';

$smarty->assign('name','Ned');

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

Technical Note: In our example, we are setting absolute paths to all of the Smarty directories. If '/web/www.mydomain.com/smarty/guestbook/' is within your PHP include_path, then these settings are not necessary. However, it is more efficient and (from experience) less error-prone to set them to absolute paths. This ensures that Smarty is getting files from the directories you intended.

技术提示:
在我们的例子里,已经设置了所有Smarty目录的绝对目录。如果 '/web/www.mydomain.com/smarty/guestbook/' 已经包括在 include_path里了,那么这些设置则没有必要。但是,从经验和通用性看来,为避免发生错误,还是配置一下为好。

Now load the index.php file from your web browser. You should see "Hello, Ned!"
现在在浏览器打开 index.php,你应该看到"Hello, Porky!"

You have completed the basic setup for Smarty!
你现在已经完成了Smarty的基本设置,恭喜!!

Prev | Home | Next
Installation 安装 | Up | Extended Setup 扩展配置


Extended Setup

Prev

Chapter 2. Installation
第二章.安装

 Next

Extended Setup
扩展设置

This is a continuation of the basic installation, please read that first!
这是基本安装的继续,请先阅读那个文件!

A slightly more flexible way to setup Smarty is to extend the class and initialize your Smarty environment. So instead of repeatedly setting directory paths, assigning the same vars, etc., we can do that in one place. Lets create a new directory "/php/includes/guestbook/" and make a new file called "setup.php". In our example environment, "/php/includes" is in our include_path. Be sure you set this up too, or use absolute file paths.

一个更灵活一点的配置Smarty的方法是扩展类,和初始化你的smarty环境。
为了避免重复地配置路径,我们可以在一个文件里配置这些变量。
我们创建一个目录 "/php/includes/guestbook/" 建立一个文件"setup.php"
同样先设置好smarty路径。

Example 2-10. Editing /php/includes/guestbook/setup.php
例2-10.编辑 /php/includes/guestbook/setup.php

// load Smarty library
require('Smarty.class.php');

// The setup.php file is a good place to load
// required application library files, and you
// can do that right here. An example:
// require('guestbook/guestbook.lib.php');是一个很好的加载应用程序的类库文件(就是扩展类)
//例如你可以在index文件里包含它

class Smarty_GuestBook extends Smarty {

 function Smarty_GuestBook() {

         // Class Constructor. These automatically get set with each new instance.
 //类构造函数.创建实例的时候自动配置

        $this->Smarty();

        $this->template_dir = '/web/www.mydomain.com/smarty/guestbook/templates/';
        $this->compile_dir = '/web/www.mydomain.com/smarty/guestbook/templates_c/';
        $this->config_dir = '/web/www.mydomain.com/smarty/guestbook/configs/';
        $this->cache_dir = '/web/www.mydomain.com/smarty/guestbook/cache/';

        $this->caching = true;
        $this->assign('app_name','Guest Book');
 }

}

Now lets alter the index.php file to use setup.php:
现在我们针对setup文件更改一下index文件

Example 2-11. Editing /web/www.mydomain.com/docs/guestbook/index.php
例 2-11.编辑/web/www.mydomain.com/docs/guestbook/index.php

require('guestbook/setup.php');

$smarty = new Smarty_GuestBook;

$smarty->assign('name','Ned');

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

Now you see it is quite simple to bring up an instance of Smarty, just use Smarty_GuestBook which automatically initializes everything for our application.
现在你看到创建一个使用smarty的实例有多么的简单.从Smarty_GuestBook开始,重新构建我们的应用程序吧^_^

Prev | Home | Next
Basic Installation 基本安装 | Up | Smarty For Template Designers 模板设计者篇


Smarty For Template Designers

Prev Next

II. Smarty For Template Designers
模板设计者篇

Table of Contents[内容列表]
3. Basic Syntax [基本语法]
4. Variables [变量]
5. Variable Modifiers [变量修改器]
6. Combining Modifiers [组合修改器]
7. Built-in Functions [内建函数]
8. Custom Functions [自定义函数]
9. Config Files [配置文件]
10. Debugging Console [调试控制台]
Prev | Home | Next
Extended Setup [扩展设置] |  | [基本语法] Basic Syntax


Basic Syntax

Prev Next

Chapter 3. Basic Syntax

第三章.基本语法

Table of Contents[内容列表]
Comments[注释]
Functions[函数]
Attributes[属性]
Embedding Vars in Double Quotes[双引号里值的嵌入]
Math[数学运算]

All Smarty template tags are enclosed within delimiters. By default, these delimiters are { and }, but they can be changed.

所有的smarty模板标签都被加上了定界符.
默认情况下是 { 和},但它们是可被改变的.

For these examples, we will assume that you are using the default delimiters. In Smarty, all content outside of delimiters is displayed as static content, or unchanged. When Smarty encounters template tags, it attempts to interpret them, and displays the appropriate output in their place.

例如,我们假定你在使用默认定界符.
在smarty里,所有定界符以外的内容都是静态输出的,或者称之为不可改变.
当smarty遇到了模板标签,将尝试解释他们,然后再以恰当的方式输出 .

Comments[注释]

Template comments are surrounded by asterisks, and that is surrounded by the delimiter tags like so: {* this is a comment *} Smarty comments are not displayed in the final output of the template. They are used for making internal notes in the templates.

模板注释被*号包围,例如 {* this is a comment *}
smarty注释不会在模板文件的最后输出中出现.
它只是模板内在的注释.

Example 3-1. Comments

例 3-1.注释

{* Smarty *}

{* include the header file here *}
{include file="header.tpl"}

{include file=$includeFile}

{include file=#includeFile#}

{* display dropdown lists *}
<SELECT name=company>
{html_options values=$vals selected=$selected output=$output}
</SELECT>

Prev | Home | Next
Smarty For Template Designers [模板设计者篇] | Up | Functions [函数]


Functions

函数

Each Smarty tag either prints a variable or invokes some sort of function. Functions are processed and displayed by enclosing the function and its attributes into delimiters like so: {funcname attr1="val" attr2="val"}.

每一个smarty标签输出一个变量或者调用某种函数.
在定界符内 函数（用'{'包住）和其属性（用界符包住）将被处理和输出.例如:
{funcname attr1="val" attr2="val"}.

Example 3-2. function syntax

例 3-2.函数语法

{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"}

Both built-in functions and custom functions have the same syntax in the templates. Built-in functions are the inner workings of Smarty, such as {if} , {section} and {strip} . They cannot be modified. Custom functions are additional functions implemented via plugins. They can be modified to your liking, or you can add new ones. {html_options} and {html_select_date} are examples of custom functions.

在模板里无论是内建函数还是自定义函数都有相同的语法.
内建函数将在smarty内部工作,例如 {if} , {section} and {strip} .他们不能被修改.
自定义函数通过插件机制起作用,它们是附加函数. 只要你喜欢,可以随意修改.你也可以自行添加.
例如 {html_options} 和 {html_select_date}

--------------------------------------------------------------------------------

Prev | Home | Next
Basic Syntax [基本语法] | Up | Attributes [属性]


Attributes

[属性]

Most of the functions take attributes that specify or modify their behavior. Attributes to Smarty functions are much like HTML attributes. Static values don't have to be enclosed in quotes, but it is recommended for literal strings. Variables may also be used, and should not be in quotes.

大多数函数都带有自己的属性以便于明确说明或者修改他们的行为.
smarty函数的属性很像HTML中的属性.
静态数值不需要加引号,但是字符串建议使用引号.
如果用变量作属性,它们也不能加引号.

Some attributes require boolean values (true or false). These can be specified as either unquoted true, on, and yes, or false, off, and no.

一些属性用到了布尔值(真或假).
它们不需要加引号,可以是true,on,yes或者false,off,no.

Example 3-3. function attribute syntax

例 3-3.函数属性语法

{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>

Prev | Home | Next
Functions [函数] | Up | Embedding Vars in Double Quotes [双引号里值的嵌入]


Variables

Prev Next

Chapter 4. Variables[第四章.变量]
第四章.变量

Table of Contents[内容列表]
Variables assigned from PHP[从PHP分配的变量]
Variables loaded from config files[从配置文件读取的变量]
{$smarty} reserved variable[{$smarty} 保留变量]

Smarty has several different types of variables.
The type of the variable depends on what symbol it is prefixed with (or enclosed within).

Smarty有几种不同类型的变量.
变量 的类型取决于它的前缀是什么符号(或者被什么符号包围)

Variables in Smarty can be either displayed directly or used as arguments for function attributes and modifiers, inside conditional expressions, etc.
To print a variable, simply enclose it in the delimiters so that it is the only thing contained between them. Examples:

Smarty的变量可以直接被输出或者作为函数属性和修饰符（modifiers）的参数,或者用于内部的条件表达式等等.
如果要输出一个变量,只要用定界符将它括起来就可以.例如:
{$Name}

{$Contacts[row].Phone}

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

Variables assigned from PHP
从PHP分配的变量

Table of Contents[内容列表]
Associative arrays[关联数组]
Array indexes[数组下标]
Objects[对象]

Variables that are assigned from PHP are referenced by preceding them with a dollar sign $.
Variables assigned from within the template with the assign function are also displayed this way.

调用从PHP分配的变量需在前加"$"符号.（译注：同php一样）
调用模板内的assign函数分配的变量也是这样.（译注：也是用$加变量名来调用）

Example 4-1. assigned variables
例 4-1.分配的变量

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.

Prev | Home | Next
Attributes [属性] | Up | Associative arrays [关联数组]


Associative arrays

You can also reference associative array variables that are assigned from PHP by specifying the key after the '.' (period) symbol.

Example 4-2. accessing associative array variables

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>
{* you can print arrays of arrays as well *}
{$Contacts.phone.home}<br>
{$Contacts.phone.cell}<br>

OUTPUT:

555-222-9876<br>
zaphod@slartibartfast.com<br>
555-444-3333<br>
555-111-1234<br>

Prev | Home | Next
Variables | Up | Array indexes


Array indexes

You can reference arrays by their index, much like native PHP syntax.

Example 4-3. accessing arrays by index

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>
{* you can print arrays of arrays as well *}
{$Contacts[2][0]}<br>
{$Contacts[2][1]}<br>

OUTPUT:

555-222-9876<br>
zaphod@slartibartfast.com<br>
555-444-3333<br>
555-111-1234<br>

Prev | Home | Next
Associative arrays | Up | Objects


Objects

Properties of objects assigned from PHP can be referenced by specifying the property name after the '->' symbol.

Example 4-4. accessing object properties

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

OUTPUT:

name: Zaphod Beeblebrox<br>
email: zaphod@slartibartfast.com<br>

Prev | Home | Next
Array indexes | Up | Variables loaded from config files


Variables loaded from config files

Prev Chapter 4. Variables[第四章.变量] Next

Variables loaded from config files
从配置文件读取的变量

Variables that are loaded from the config files are referenced by enclosing them within hash marks (#), or with the smarty variable $smarty.config.
The second syntax is useful for embedding into quoted attribute values.

配置文件中的变量需要通过用两个"#"或者是smarty的保留变量 $smarty.config.来调用（下节将讲到）
第二种语法在变量作为属性值并被引号括住的时候非常有用.
（译注：举个例子 {include file="#includefile#"} 这样#includefile#将被当作字符处理，而不表示配置文件变量，
        但可以这样表示 {include file="`$smarty.config.includefile`"}不要忘了加``）

Example 4-5. config variables
例 4-5.从配置文件引用的变量

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#}">
    <td>First</td>
    <td>Last</td>
    <td>Address</td>
</tr>
</table>
</body>
</html>

index.tpl: (alternate syntax)

{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}">
    <td>First</td>
    <td>Last</td>
    <td>Address</td>
</tr>
</table>
</body>
</html>

OUTPUT: (same for both examples)

<html>
<title>This is mine</title>
<body bgcolor="#eeeeee">
<table border="3" bgcolor="#bbbbbb">
<tr bgcolor="#cccccc">
    <td>First</td>
    <td>Last</td>
    <td>Address</td>
</tr>
</table>
</body>
</html>

Config file variables cannot be used until after they are loaded in from a config file. This procedure is explained later in this document under {config_load} .

配置文件的变量只有在它们被加载以后才能使用.
这个过程将在以后 {config_load} . 的章节里说明.

Prev | Home | Next
Variables [变量] | Up | {$smarty} reserved variable [{$smarty} 保留变量]


{$smarty} reserved variable

Prev Chapter 4. Variables[第四章.变量] Next

{$smarty} reserved variable
{$smarty}保留变量

Table of Contents
Request variables[页面请求变量](译注：就是get,post,server,session等变量)
{$smarty.now}
{$smarty.const}
{$smarty.capture}
{$smarty.config}
{$smarty.section}, {$smarty.foreach}
{$smarty.template}

The reserved {$smarty} variable can be used to access several special template variables. The full list of them follows.

{$smarty}保留变量可以被用于访问一些特殊的模板变量.
以下是全部列表:

Prev | Home | Next
Variables loaded from config files [从配置文件读取的变量] | Up | Request variables [页面请求的变量]


Request variables

The request variables such as get, post, cookies, server, environment, and session variables can be accessed as demonstrated in the examples below:

Example 4-6. displaying request variables

{* display value of page from URL (GET) http://www.domain.com/index.php?page=foo *}
{$smarty.get.page}

{* display the variable "page" from a form (POST) *}
{$smarty.post.page}

{* display the value of the cookie "username" *}
{$smarty.cookies.username}

{* display the server variable "SERVER_NAME" *}
{$smarty.server.SERVER_NAME}

{* display the system environment variable "PATH" *}
{$smarty.env.PATH}

{* display the php session variable "id" *}
{$smarty.session.id}

{* display the variable "username" from merged get/post/cookies/server/env *}
{$smarty.request.username}

Prev | Home | Next
{$smarty} reserved variable | Up | {$smarty.now}


{$smarty.now}

The current timestamp can be accessed with {$smarty.now}. The number reflects the number of seconds passed since the so-called Epoch (January 1, 1970) and can be passed directly to date_format modifier for display purposes.

Example 4-7. using {$smarty.now}

{* use the date_format modifier to show current date and time *}
{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}

Prev | Home | Next
Request variables | Up | {$smarty.const}


{$smarty.const}

You can access PHP constant values directly.

Example 4-8. using {$smarty.const}

{$smarty.const._MY_CONST_VAL}

Prev | Home | Next
{$smarty.now} | Up | {$smarty.capture}


{$smarty.capture}

The output captured via {capture}..{/capture} construct can be accessed using {$smarty} variable. See section on capture for an example.

Prev | Home | Next
{$smarty.const} | Up | {$smarty.config}


{$smarty.config}

{$smarty} variable can be used to refer to loaded config variables. {$smarty.config.foo} is a synonym for {#foo#}. See the section on config_load for an example.

Prev | Home | Next
{$smarty.capture} | Up | {$smarty.section}, {$smarty.foreach}


{$smarty.section}, {$smarty.foreach}

{$smarty} variable can be used to refer to 'section' and 'foreach' loop properties. See docs for section and foreach.

Prev | Home | Next
{$smarty.config} | Up | {$smarty.template}


{$smarty.template}

This variable contains the name of the current template being processed.

Prev | Home | Next
{$smarty.section}, {$smarty.foreach} | Up | Variable Modifiers


Variable Modifiers

Prev Next

Chapter 5. Variable Modifiers [变量调节器]

Table of Contents [内容列表]
capitalize
count_characters
cat
count_paragraphs
count_sentences
count_words
date_format
default
escape
indent
lower
nl2br
regex_replace
replace
spacify
string_format
strip
strip_tags
truncate
upper
wordwrap

Variable modifiers can be applied to variables, custom functions or strings. To apply a modifier, specify the value followed by the | (pipe) and the modifier name. A modifier may accept additional parameters that affect its behavior. These parameters follow the modifer name and are separated by : (colon).
变量调节器用于变量，自定义函数和字符串。 请使用‘|’符号和调节器名称应用调节器。 变量调节器由赋予的参数值决定其行为。 参数由‘：’符号分开。

Example 5-1. modifier example
例 5-1.调节器的例子

{* Uppercase the title *}

<h2>{$title|upper}</h2>

{* Truncate the topic to 40 characters use ... at the end *}
Topic: {$topic|truncate:40:"..."}

{* format a literal string *}
{"now"|date_format:"%Y/%m/%d"}

{* apply modifier to a custom function *}
{mailto|upper address="me@domain.dom"}

If you apply a modifier to an array variable instead of a single value variable, the modifier will be applied to every value in that array. If you really want the modifier to work on an entire array as a value, you must prepend the modifier name with an @ symbol like so: {$articleTitle|@count} (this will print out the number of elements in the $articleTitle array.)
如果你给数组变量应用单值变量的调节，结果是数组的每个值都被调节。 如果你只想要调节器用一个值调节整个数组，你必须在调节器名字前加上@符号。 例如： {$articleTitle|@count}（这将会在 $articleTitle 数组里输出元素的数目）

Modifiers can be autoloaded from your $plugins_dir (also see: Naming Conventions) or can be registered explicitely (see: register_modifier). Additionally all php-functions can be used as modifiers implicitely. (The @count-example above actually uses php's count-function and not a smarty-modifier). Using php-functions as modifiers has two little pitfalls: First: Sometimes the order of the function-parameters is not the desirable one ({"%2.f"|sprintf:$float} actually works, but asks for the more intuitive {For example: $float|string_format:"%2.f"} that is provided by the Smarty distribution). Second: with $security turned on all php-functions that are to be used as modifiers have to be declared trusted in the $security_settings['MODIFIER_FUNCS']-array.

capitalize

This is used to capitalize the first letter of all words in a variable.
将变量里的所有单词首字大写。

Example 5-2. capitalize
例 5-2.首字大写

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Police begin campaign to rundown jaywalkers.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|capitalize}

OUTPUT:

Police begin campaign to rundown jaywalkers.
Police Begin Campaign To Rundown Jaywalkers.

Prev | Home | Next
{$smarty.template} | Up | [计算字符数] count_characters


count_characters

Prev Chapter 5. Variable Modifiers Next

count_characters[字符计数]

Parameter Position | Type | Required | Default | Description
1 | boolean | No | false | This determines whether or not to include whitespace characters in the count. 决定是否计算空格字符。

This is used to count the number of characters in a variable.
计算变量里的字符数

Example 5-3. count_characters

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Cold Wave Linked to Temperatures.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|count_characters}
{$articleTitle|count_characters:true}

OUTPUT输出:

Cold Wave Linked to Temperatures.
29
33

Prev | Home | Next
Variable Modifiers | Up | cat


cat

Prev Chapter 5. Variable Modifiers Next

cat[连接字符串]

Parameter Position | Type | Required | cat | Description
1 | string | No | empty | This value to catentate to the given variable. 将cat里的值连接到给定的变量后面.

This value is concatenated to the given variable.
将cat里的值连接到给定的变量后面.

Example 5-4. cat

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Psychics predict world didn't end");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle|cat:" yesterday."}

OUTPUT:

Psychics predict world didn't end yesterday.

Prev | Home | Next
count_characters | Up | count_paragraphs


count_paragraphs

Prev Chapter 5. Variable Modifiers Next

count_paragraphs[计算段数]

This is used to count the number of paragraphs in a variable.
计算变量里的段落数量。

Example 5-5. count_paragraphs

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "War Dims Hope for Peace. Child's Death Ruins
Couple's Holiday.\n\nMan is Fatally Slain. Death Causes Loneliness, Feeling of Isolation.");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|count_paragraphs}

OUTPUT:

War Dims Hope for Peace. Child's Death Ruins Couple's Holiday.

Man is Fatally Slain. Death Causes Loneliness, Feeling of Isolation.
2

Prev | Home | Next
cat | Up | count_sentences


count_sentences

Prev Chapter 5. Variable Modifiers Next

count_sentences[计算句数]

This is used to count the number of sentences in a variable.
计算变量里句子的数量。

Example 5-6. count_sentences

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Two Soviet Ships Collide - One Dies. Enraged Cow Injures Farmer with Axe.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|count_sentences}

OUTPUT:

Two Soviet Ships Collide - One Dies. Enraged Cow Injures Farmer with Axe.
2

Prev | Home | Next
count_paragraphs | Up | count_words


count_words

Prev Chapter 5. Variable Modifiers Next

count_words[计算词数]

This is used to count the number of words in a variable.
计算变量里的词数 。

Example 5-7. count_words

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Dealers Will Hear Car Talk at Noon.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|count_words}

OUTPUT:

Dealers Will Hear Car Talk at Noon.
7

Prev | Home | Next
count_sentences | Up | date_format


date_format

Prev Chapter 5. Variable Modifiers Next

date_format[格式化日期]

Parameter Position | Type | Required | Default | Description
1 | string | No | %b %e, %Y | This is the format for the outputted date. 输出日期的格式。
2 | string | No | n/a | This is the default date if the input is empty. 输入为空时的默认时间格式。

This formats a date and time into the given strftime() format.
Dates can be passed to Smarty as unix timestamps, mysql timestamps or any string made up of month day year (parsable by strtotime).
Designers can then use date_format to have complete control of the formatting of the date.
If the date passed to date_format is empty and a second parameter is passed, that will be used as the date to format.

格式化从函数strftime()获得的时间和日期。
Unix或者mysql等的时间戳记(parsable by strtotime)都可以传递到smarty。
设计者可以使用date_format完全控制日期格式。
如果传给date_format的数据是空的,将使用第二个参数作为时间格式。

Example 5-8. date_format[日期格式]

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"}

OUTPUT:

Feb 6, 2001
Tuesday, February 6, 2001
14:33:00
Feb 5, 2001
Monday, February 5, 2001
14:33:00

Example 5-9. date_format conversion specifiers[日期转换说明]

%a - abbreviated weekday name according to the current locale
（根据当地格式输出“星期”缩写格式）

%A - full weekday name according to the current locale
（根据当地格式输出“星期”全称格式）

%b - abbreviated month name according to the current locale
（根据当地格式输出“月”缩写格式）

%B - full month name according to the current locale
（根据当地格式输出“月”全称格式）

%c - preferred date and time representation for the current locale

%C - century number (the year divided by 100 and truncated to an integer, range 00 to 99)

%d - day of the month as a decimal number (range 00 to 31)

%D - same as %m/%d/%y

%e - day of the month as a decimal number, a single digit is preceded by a
space (range 1 to 31)

%g - Week-based year within century [00,99]

%G - Week-based year, including the century [0000,9999]

%h - same as %b

%H - hour as a decimal number using a 24-hour clock (range 00 to 23)

%I - hour as a decimal number using a 12-hour clock (range 01 to 12)

%j - day of the year as a decimal number (range 001 to 366)

%k - Hour (24-hour clock) single digits are preceded by a blank. (range 0 to 23)

%l - hour as a decimal number using a 12-hour clock, single digits preceeded by
a space (range 1 to 12)

%m - month as a decimal number (range 01 to 12)

%M - minute as a decimal number

%n - newline character

%p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale

%r - time in a.m. and p.m. notation

%R - time in 24 hour notation

%S - second as a decimal number

%t - tab character

%T - current time, equal to %H:%M:%S

%u - weekday as a decimal number [1,7], with 1 representing Monday

%U - week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week

%V - The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1
is the first week that has at least 4 days in the current year, and with Monday as the first day of the week.

%w - day of the week as a decimal, Sunday being 0

%W - week number of the current year as a decimal number, starting with the first Monday as the first day of the first week

%x - preferred date representation for the current locale without the time

%X - preferred time representation for the current locale without the date

%y - year as a decimal number without a century (range 00 to 99)

%Y - year as a decimal number including the century

%Z - time zone or name or abbreviation

%% - a literal `%' character

PROGRAMMERS NOTE: date_format is essentially a wrapper to PHP's strftime()
function. You may have more or less conversion specifiers available depending
on your system's strftime() function where PHP was compiled. Check your
system's manpage for a full list of valid specifiers.

程序员提示:date_format本质上是php的strftime()函数的一个包装。
当php被编译的时候你可以或多或少的依靠系统的strftime()转换有效的区分符。
可以查看系统手册的有效区分符的全表.

Prev | Home | Next
count_words | Up | default


default

Prev Chapter 5. Variable Modifiers Next

default[默认值]

Parameter Position | Type | Required | Default | Description
1 | string | No | empty | This is the default value to output if the variable is empty. 这是变量为空的时候的默认输出。

This is used to set a default value for a variable. If the variable is empty or unset, the given default value is printed instead. Default takes one argument.
为空变量设置一个默认值。
当变量为空或者未分配的时候,将由给定的默认值替代输出。

Example 5-10. default

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Dealers Will Hear Car Talk at Noon.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle|default:"no title"}
{$myTitle|default:"no title"}

OUTPUT:

Dealers Will Hear Car Talk at Noon.
no title

Prev | Home | Next
date_format | Up | escape


escape

Prev Chapter 5. Variable Modifiers Next

escape[编码]

Parameter Position | Type | Required | Possible Values | Default | Description
1 | string | No | html,htmlall,url,quotes,hex,hexentity,javascript | html | This is the escape format to use. 使用何种编码格式。

This is used to html escape, url escape, escape single quotes on a variable not already escaped, hex escape, hexentity or javascript escape. By default, the variable is html escaped.
用于html转码,url转码,在没有转码的变量上转换单引号,十六进制转码,十六进制美化,或者javascript转码。默认是html转码。

Example 5-11. escape

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "'Stiff Opposition Expected to Casketless Funeral Plan'");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|escape}
{$articleTitle|escape:"html"} {* escapes & " ' < > *}
{$articleTitle|escape:"htmlall"} {* escapes ALL html entities *}
{$articleTitle|escape:"url"}
{$articleTitle|escape:"quotes"}
<a href="mailto:{$EmailAddress|escape:"hex"}">{$EmailAddress|escape:"hexentity"}</a>

OUTPUT:

'Stiff Opposition Expected to Casketless Funeral Plan'
&#039;Stiff Opposition Expected to Casketless Funeral Plan&#039;
&#039;Stiff Opposition Expected to Casketless Funeral Plan&#039;
&#039;Stiff Opposition Expected to Casketless Funeral Plan&#039;
%27Stiff+Opposition+Expected+to+Casketless+Funeral+Plan%27
\'Stiff Opposition Expected to Casketless Funeral Plan\'
<a href="mailto:%62%6f%62%40%6d%65%2e%6e%65%74">&#x62;&#x6f;&#x62;&#x40;&#x6d;&#x65;&#x2e;&#x6e;&#x65;&#x74;</a>

Prev | Home | Next
default | Up | indent


indent

Prev Chapter 5. Variable Modifiers Next

indent[缩进]

Parameter Position | Type | Required | Default | Description
1 | integer | No | 4 | This determines how many characters to indent to. 决定缩进多少个字符。
2 | string | No | (one space) | This is the character used to indent with.使用什么字符来代替缩进。

This indents a string at each line, default is 4. As an optional parameter, you can specify the number of characters to indent. As an optional second parameter, you can specify the character to use to indent with. (Use "\t" for tabs.)
在每行缩进字符串，默认是4个字符。
作为可选参数，你可以指定缩进字符数。
作为第二个可选参数，你可以指定缩进用什么字符代替。

特别提示：使用缩进时如果是在HTML中，则需要使用& n b s p;(空格)来代替缩进，否则没有效果。

Example 5-12. indent

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'NJ judge to rule on nude beach.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}

{$articleTitle|indent}

{$articleTitle|indent:10}

{$articleTitle|indent:1:"\t"}

OUTPUT:

NJ judge to rule on nude beach.
Sun or rain expected today, dark tonight.
Statistics show that teen pregnancy drops off significantly after 25.

 NJ judge to rule on nude beach.
 Sun or rain expected today, dark tonight.
 Statistics show that teen pregnancy drops off significantly after 25.

 NJ judge to rule on nude beach.
 Sun or rain expected today, dark tonight.
 Statistics show that teen pregnancy drops off significantly after 25.

    NJ judge to rule on nude beach.
    Sun or rain expected today, dark tonight.
    Statistics show that teen pregnancy drops off significantly after 25.

Prev | Home | Next
escape | Up | lower


lower

Prev Chapter 5. Variable Modifiers[变量调节器] Next

lower
小写

This is used to lowercase a variable.
将变量字符串小写

Example 5-13. lower
例 5-13.小写

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Two Convicts Evade Noose, Jury Hung.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|lower}

OUTPUT:

Two Convicts Evade Noose, Jury Hung.
two convicts evade noose, jury hung.

Prev | Home | Next
indent[缩进] | Up | nl2br换行符替换成<br />


nl2br

Prev Chapter 5. Variable Modifiers[变量调节器] Next

nl2br
换行符替换成<br />

All linebreaks will be converted to <br /> tags in the given variable. This is equivalent to the PHP nl2br() function.

所有的换行符将被替换成 <br />.功能同PHP中的nl2br()函数一样.

Example 5-14. nl2br
例 5-14.换行符替换成<br />

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Sun or rain expected\ntoday, dark tonight");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle|nl2br}

OUTPUT:

Sun or rain expected<br />today, dark tonight

Prev | Home | Next
lower[小写] | Up | regex_replace[正则替换]


regex_replace

Prev Chapter 5. Variable Modifiers[变量调节器] Next

regex_replace
正则替换

Parameter Position参数位置 | Type类型 | Required必需 | Default默认 | Description
1 | string | Yes | n/a | This is the regular expression to be replaced. 替换正则表达式.
2 | string | Yes | n/a | This is the string of text to replace with. 用来替换的文本字串

A regular expression search and replace on a variable. Use the syntax for preg_replace() from the PHP manual.

寻找和替换正则表达式 .
欲使用其语法，请参考Php手册中的preg_replace()函数.

Example 5-15. regex_replace
例 5-15.正则替换

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Infertility unlikely to\nbe passed on, experts say.");
$smarty->display('index.tpl');

index.tpl:

{* replace each carriage return, tab & new line with a space *}
{* 使用空格替换每个回车,tab,和换行符 *}
{$articleTitle}
{$articleTitle|regex_replace:"/[\r\t\n]/":" "}

OUTPUT:

Infertility unlikely to
 be passed on, experts say.
Infertility unlikely to be passed on, experts say.

Prev | Home | Next
nl2br[替换\n为</br> | Up | replace[替换]


replace

Prev Chapter 5. Variable Modifiers[变量调节器] Next

replace
替换

Parameter Position参数位置 | Type参数类型 | Required必需 | Default默认 | Description
1 | string | Yes | n/a | This is the string of text to be replaced. 将被替换的文本字串
2 | string | Yes | n/a | This is the string of text to replace with. 用来替换的文本字串

A simple search and replace on a variable.
简单的搜索和替换字符串

Example 5-16. replace
例 5-16.替换

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Child's Stool Great for Use in Garden.");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|replace:"Garden":"Vineyard"}
{$articleTitle|replace:" ":" "}

OUTPUT:

Child's Stool Great for Use in Garden.
Child's Stool Great for Use in Vineyard.
Child's Stool Great for Use in Garden.

Prev | Home | Next
regex_replace[正则替换] | Up | spacify[插空]


spacify

Prev Chapter 5. Variable Modifiers[变量调节器] Next

spacify
插空

Parameter Position参数位置 | Type参数类型 | Required必需 | Default默认 | Description描述
1 | string | No | one space | This what gets inserted between each character of the variable. 将在两个字符之间插入的字符（串）

spacify is a way to insert a space between every character of a variable. You can optionally pass a different character (or string) to insert.

插空(不知道这个词是什么意思,顾名思义了^^)是一种在字符串的每个字符之间插入空格或者其他的字符(串).

Example 5-17. spacify
例 5-17.插空

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Something Went Wrong in Jet Crash, Experts Say.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|spacify}
{$articleTitle|spacify:"^^"}

OUTPUT:

Something Went Wrong in Jet Crash, Experts Say.
S o m e t h i n g W e n t W r o n g i n J e t C r a s h , E x p e r t s S a y .
S^^o^^m^^e^^t^^h^^i^^n^^g^^ ^^W^^e^^n^^t^^ ^^W^^r^^o^^n^^g^^ ^^i^^n^^ ^^J^^e^^t^^ ^^C^^r^^a^^s^^h^^,^^ ^^E^^x^^p^^e^^r^^t^^s^^ ^^S^^a^^y^^.

Prev | Home | Next
replace[替换] | Up | string_format[字符串格式化]


string_format

Prev Chapter 5. Variable Modifiers[变量调节器] Next

string_format
字符串格式化

Parameter Position参数位置 | Type参数类型 | Required必需 | Default默认 | Description描述
1 | string | Yes | n/a | This is what format to use. (sprintf) 使用的格式化方式

This is a way to format strings, such as decimal numbers and such. Use the syntax for sprintf for the formatting.

是一种格式化字符串的方法.例如格式化为十进制数等等.使用sprintf语法格式化

Example 5-18. string_format
字符串格式化

index.php:

$smarty = new Smarty;
$smarty->assign('number', 23.5787446);
$smarty->display('index.tpl');

index.tpl:

{$number}
{$number|string_format:"%.2f"}
{$number|string_format:"%d"}

OUTPUT:

23.5787446
23.58
24

Prev | Home | Next
spacify[插空] | Up | strip[去除(多余空格)]


strip

Prev Chapter 5. Variable Modifiers[变量调节器] Next

strip
去除(多余空格)

This replaces all repeated spaces, newlines and tabs with a single space, or with a supplied string.

用一个空格或一个给定字符替换所有重复空格,换行和制表符.

Note: If you want to strip blocks of template text, use the strip function.

注意:如果想要去除模板文本中的区块,请使用 strip函数

Example 5-19. strip
例 5-19.去除(多余空格)

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Grandmother of\neight makes\t hole in one.");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|strip}
{$articleTitle|strip:"&nbsp;"}

OUTPUT:

Grandmother of
eight makes hole in one.
Grandmother of eight makes hole in one.
Grandmother&nbsp;of&nbsp;eight&nbsp;makes&nbsp;hole&nbsp;in&nbsp;one.

Prev | Home | Next
string_format[字串格式化] | Up | strip_tags[去除html标签]


strip_tags

Prev Chapter 5. Variable Modifiers[变量调节器] Next

strip_tags
去除html标签

This strips out markup tags, basically anything between < and >.

去除<和>标签,包括在<和>之间的任何内容.

Example 5-20. strip_tags
例 5-20.去除Html标签

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Blind Woman Gets <font face=\"helvetica\">New Kidney</font> from Dad she Hasn't Seen in <b>years</b>.");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|strip_tags}

OUTPUT:

Blind Woman Gets <font face="helvetica">New Kidney</font> from Dad she Hasn't Seen in <b>years</b>.
Blind Woman Gets New Kidney from Dad she Hasn't Seen in years.

Prev | Home | Next
strip[去除(多余空格)] | Up | truncate[截取]


truncate

Prev Chapter 5. Variable Modifiers[变量调节器] Next

truncate
截取

Parameter Position参数位置 | Type参数类型 | Required必需 | Default默认 | Description描述
1 | integer | No | 80 | This determines how many characters to truncate to. 截取字符的数量
2 | string | No | ... | This is the text to append if truncation occurs. 截取后追加在截取词后面的字符串
3 | boolean | No | false | This determines whether or not to truncate at a word boundary (false), or at the exact character (true). 是截取到词的边界（假）还是精确到字符（真）

This truncates a variable to a character length, default is 80.
As an optional second parameter, you can specify a string of text to display at the end if the variable was truncated. The characters in the string are included with the original truncation length.
By default, truncate will attempt to cut off at a word boundary.
If you want to cut off at the exact character length, pass the optional third parameter of true.

从字符串开始处截取某长度的字符.默认是80个.
你也可以指定第二个参数作为追加在截取字符串后面的文本字串.该追加字串被计算在截取长度中。
默认情况下,smarty会截取到一个词的末尾。
如果你想要精确的截取多少个字符,把第三个参数改为"true"

Example 5-21. truncate
例5-21.截取

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...

Prev | Home | Next
strip_tags[去除Html标签] | Up | upper[大写]


upper

Prev Chapter 5. Variable Modifiers[变量调节器] Next

upper
大写

This is used to uppercase a variable.

将变量改为大写

Example 5-22. upper
例 5-22.大写

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "If Strike isn't Settled Quickly it may Last a While.");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|upper}

OUTPUT:

If Strike isn't Settled Quickly it may Last a While.
IF STRIKE ISN'T SETTLED QUICKLY IT MAY LAST A WHILE.

Prev | Home | Next
truncate[截取] | Up | wordwrap[行宽约束]


wordwrap

Prev Chapter 5. Variable Modifiers[变量调节器] Next

wordwrap
行宽约束

Parameter Position | Type | Required | Default | Description
1 | integer | No | 80 | This determines how many columns to wrap to. 指定段落(句子)的宽度
2 | string | No | \n | This is the string used to wrap words with. 使用什么字符约束
3 | boolean | No | false | This determines whether or not to wrap at a word boundary (false), or at the exact character (true). 是约束到词的边界（假）还是精确到字符（真）

This wraps a string to a column width, default is 80.
As an optional second parameter, you can specify a string of text to wrap the text to the next line (default is carriage return \n).
By default, wordwrap will attempt to wrap at a word boundary. If you want to cut off at the exact character length, pass the optional third parameter of true.

可以指定段落的宽度(也就是多少个字符一行,超过这个字符数换行).默认80.
第二个参数可选,可以指定在约束点使用什么字符(默认是换行符\n).
默认情况下smarty将截取到词尾,如果想精确到设定长度的字符，请将第三个参数设为ture

Example 5-23. wordwrap
例 5-23.行宽约束

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Blind woman gets new kidney from dad she hasn't seen in years.");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}

{$articleTitle|wordwrap:30}

{$articleTitle|wordwrap:20}

{$articleTitle|wordwrap:30:"<br>\n"}

{$articleTitle|wordwrap:30:"\n":true}

OUTPUT:

Blind woman gets new kidney from dad she hasn't seen in years.

Blind woman gets new kidney
from dad she hasn't seen in
years.

Blind woman gets new
kidney from dad she
hasn't seen in
years.

Blind woman gets new kidney<br>
from dad she hasn't seen in years.

Blind woman gets new kidney fr
om dad she hasn't seen in year
s.

Prev | Home | Next
upper[大写] | Up | Combining Modifiers[组合使用调节器]


Combining Modifiers

Prev[前一页] Next[后一页]

Chapter 6. Combining Modifiers
第6章。组合修改器

You can apply any number of modifiers to a variable. They will be applied in the order they are combined, from left to right. They must be separated with a | (pipe) character.
对于同一个变量，你可以使用多个修改器。它们将从左到右按照设定好的顺序被依次组合使用。使用时必须要用"|"字符作为它们之间的分隔符。

Example 6-1. combining modifiers
例 6-1.组合修改器

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. . .

Prev[前一页] | Home[主目录] | Next[下一页]
wordwrap[行宽约束] | Up[单元目录] | Built-in Functions[内嵌函数]


Built-in Functions

Smarty - php 模板编译引擎
Prev Next

Chapter 7. Built-in Functions[第七章.内建函数]

Table of Contents
capture
config_load
foreach,foreachelse
include
include_php
insert
if,elseif,else
ldelim,rdelim
literal
php
section,sectionelse
strip

Smarty comes with several built-in functions. Built-in functions are integral to the template language. You cannot create custom functions with the same names, nor can you modify built-in functions.

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

capture

Attribute Name | Type | Required | Default | Description
name | string | no | default | The name of the captured block
assign | string | No | n/a | The variable name where to assign the captured output to

属性 | 类型 | 是否必须 | 缺省值 | 描述
name | string | no | default | 数据采集区域名称
assign | string | No | n/a | 数据采集区域在哪分配给变量name[待考]

capture is used to collect the output of the template into a variable instead of displaying it. Any content between {capture name="foo"} and {/capture} is collected into the variable specified in the name attribute. The captured content can be used in the template from the special variable $smarty.capture.foo where foo is the value passed in the name attribute. If you do not supply a name attribute, then "default" will be used. All {capture} commands must be paired with {/capture}. You can nest capture commands.

capture函数的作用是捕获模板输出的数据并将其存储到一个变量里,而不是把它们输出到页面.
任何在 {capture name="foo"}和{/capture}之间的数据将被存储到变量$foo中，该变量由name属性指定.
在模板中通过 $smarty.capture.foo 访问该变量.
如果没有指定 name 属性,函数默认将使用 "default" 作为参数.
{capture}必须成对出现，即以{/capture}作为结尾,该函数不能嵌套使用.

Technical Note: Smarty 1.4.0 - 1.4.4 placed the captured content into the variable named $return. As of 1.4.5, this behavior was changed to use the name attribute, so update your templates accordingly.

技术提示:
Smarty 1.4.0 - 1.4.4 版把捕获到的内容存储于 $return 变量里.
在 1.4.5 版以后就将该数据保存到了由 name 属性指定的变量里.请升级你的模板.

Caution

Be careful when capturing {insert} output. If you have caching turned on and you have {insert} commands that you expect to run within cached content, do not capture this content.

警告

当希望捕获包含 {insert} 命令的数据时要特别注意. 如果打开了缓存并希望将 {insert} 命令输出到缓存中，不要捕获该区域的数据.

Example 7-1. capturing template content
例 7-1.捕获模板内容

{* we don't want to print a table row unless content is displayed *}
{* 该例在捕获到内容后输出一行包含数据的表格，如果没有捕获到就什么也不输出 *}
{capture name=banner}
{include file="get_banner.tpl"}
{/capture}
{if $smarty.capture.banner ne ""}
    <tr>
        <td>
            {$smarty.capture.banner}
        </td>
    </tr>
{/if}

Prev | Home | Next
Combining Modifiers | Up | config_load


config_load

Attribute Name | Type | Required | Default | Description
file | string | Yes | n/a | The name of the config file to include
section | string | No | n/a | The name of the section to load
scope | string | no | local | How the scope of the loaded variables are treated, which must be one of local, parent or global. local means variables are loaded into the local template context. parent means variables are loaded into both the local context and the parent template that called it. global means variables are available to all templates.
global | boolean | No | No | Whether or not variables are visible to the parent template, same as scope=parent. NOTE: This attribute is deprecated by the scope attribute, but still supported. If scope is supplied, this value is ignored.

属性 | 类型 | 是否必须 | 缺省值 | 描述
file | string | Yes | n/a | 待包含的配置文件的名称
section | string | No | n/a | 配置文件中待加载部分的名称
scope | string | no | local | 加载数据的作用域，取值必须为local, parent 或 global. local 说明该变量的作用域为当前模板. parent 说明该变量的作用域为当前模板和当前模板的父模板(调用当前模板的模板). global 说明该变量的作用域为所有模板.
global | boolean | No | No | 说明加载的变量是否全局可见，等同于 scope=parent. 注意: 当指定了 scope 属性时，可以设置该属性，但模板忽略该属性值而以 scope 属性为准。

This function is used for loading in variables from a configuration file into the template. See Config Files for more info.
该函数用于从配置文件中加载变量. 更多信息请查看 配置文件.

Example 7-2. function config_load
例 7-2.演示 config_load 函数

{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>

Config files may also contain sections. You can load variables from within a section with the added attribute section .

配置文件有可能包含多个部分，此时可以使用附加属性 section 指定从哪一部分中取得变量.

NOTE: Config file sections and the built-in template function called section have nothing to do with each other, they just happen to share a common naming convention.

注意：配置文件中的 section 和模板内建函数 section 只是命名相同，毫不相干。

Example 7-3. function config_load with section
例 7-3. 带 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>

Prev | Home | Next
Built-in Functions | Up | foreach,foreachelse


foreach,foreachelse

Table of Contents目录
iteration
first
last
show
total

Attribute Name | Type | Required | Default | Description
from | string | Yes | n/a | The name of the array you are looping through
item | string | Yes | n/a | The name of the variable that is the current element
key | string | No | n/a | The name of the variable that is the current key
name | string | No | n/a | The name of the foreach loop for accessing foreach properties

属性 | 类型 | 是否必须 | 缺省值 | 描述
from | string | Yes | n/a | 待循环数组的名称
item | string | Yes | n/a | 当前处理元素的变量名称
key | string | No | n/a | 当前处理元素的键名
name | string | No | n/a | 该循环的名称，用于访问该循环

foreach loops are an alternative to section loops. foreach is used to loop over a single associative array. The syntax for foreach is much easier than section , but as a tradeoff it can only be used for a single array. foreach tags must be paired with /foreach tags. Required parameters are from and item . The name of the foreach loop can be anything you like, made up of letters, numbers and underscores. foreach loops can be nested, and the nested foreach names must be unique from each other. The from variable (usually an array of values) determines the number of times foreach will loop. foreachelse is executed when there are no values in the from variable.

foreach 是除 section 之外处理循环的另一种方案(根据不同需要选择不同的方案).
foreach 用于处理简单数组(数组中的元素的类型一致)，它的格式比 section 简单许多，缺点是只能处理简单数组.
foreach 必须和 /foreach 成对使用，且必须指定 from 和 item 属性.
name 属性可以任意指定(字母、数字和下划线的组合).
foreach 可以嵌套，但必须保证嵌套中的 foreach 名称唯一.
from 属性(通常是数组)决定循环的次数.
foreachelse 语句在 from 变量没有值的时候被执行.

Example 7-4. foreach
例 7-4. foreach 演示

{* this example will print out all the values of the $custid array *}
{* 该例将输出数组 $custid 中的所有元素的值 *}
{foreach from=$custid item=curr_id}
    id: {$curr_id}<br>
{/foreach}

OUTPUT:

id: 1000<br>
id: 1001<br>
id: 1002<br>

Example 7-5. foreach key
例 7-5. foreach 键的演示

{* The key contains the key for each looped value

assignment looks like this:

$smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"),
 array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")));
*}
{* 键就是数组的下标，请参看关于数组的解释 *}

{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>

Foreach-loops also have their own variables that handle foreach properties. These are indicated like so: {$smarty.foreach.foreachname.varname} with foreachname being the name specified as the name attribute of foreach

foreach 循环有自己的变量名，使用该变量名可以访问该循环. 使用方法为{$smarty.foreach.foreachname.varname}，其中 foreachname 即在 foreach 中指定的 name 属性.

Prev | Home | Next
config_load | Up | iteration


include

Attribute Name | Type | Required | Default | Description
file | string | Yes | n/a | The name of the template file to include
assign | string | No | n/a | The name of the variable that the output of include will be assigned to
[var ...] | [var type] | No | n/a | variable to pass local to template

属性 | 类型 | 是否必须 | 缺省值 | 描述
file | string | Yes | n/a | 待包含的模板文件名
assign | string | No | n/a | 该属性指定一个变量保存待包含模板的输出
[var ...] | [var type] | No | n/a | 传递给待包含模板的本地参数，只在待包含模板中有效

Include tags are used for including other templates in the current template. Any variables available in the current template are also available within the included template. The include tag must have the attribute "file", which contains the template resource path.

Include 标签用于在当前模板中包含其它模板. 当前模板中的变量在被包含的模板中可用. 必须指定 file 属性，该属性指明模板资源的位置.

You can optionally pass the assign attribute, which will specify a template variable name that the output of include will be assigned to instead of displayed.

如果设置了 assign 属性，该属性对应的变量名用于保存待包含模板的输出，这样待包含模板的输出就不会直接显示了。

Example 7-6. function include
例 7-6. include 函数演示

{include file="header.tpl"}

{* body of template goes here *}

{include file="footer.tpl"}

You can also pass variables to included templates as attributes. Any variables explicitly passed to an included template as attributes are only available within the scope of the included file. Attribute variables override current template variables, in the case they are named alike.

可以在属性中传递参数给待包含模板. 传递给待包含模板的参数只在待包含模板中可见. 如果传递的参数在待包含模板中有同名变量，那么该变量被传递的参数替代.

Example 7-7. function include passing variables
例 7-7. 带传递参数的 include 函数演示

{include file="header.tpl" title="Main Menu" table_bgcolor="#c0c0c0"}

{* body of template goes here *}

{include file="footer.tpl" logo="http://my.domain.com/logo.gif"}

Use the syntax for template resources to include files outside of the $template_dir directory.

包含 $template_dir 文件夹之外的模板请使用 模板资源 说明的格式.

Example 7-8. function include template resource examples
例 7-8. 使用外部模板资源的 include 函数演示

{* absolute filepath *}
{include file="/usr/local/include/templates/header.tpl"}

{* absolute filepath (same thing) *}
{include file="file:/usr/local/include/templates/header.tpl"}

{* windows absolute filepath (MUST use "file:" prefix) *}
{include file="file:C:/www/pub/templates/header.tpl"}

{* include from template resource named "db" *}
{include file="db:header.tpl"}

Prev | Home | Next
total | Up | include_php


include_php

Attribute Name | Type | Required | Default | Description
file | string | Yes | n/a | The name of the php file to include
once | boolean | No | true | whether or not to include the php file more than once if included multiple times
assign | string | No | n/a | The name of the variable that the output of include_php will be assigned to

属性 | 类型 | 是否必须 | 缺省值 | 描述
file | string | Yes | n/a | 待包含php文件的名称
once | boolean | No | true | 如果待包含php文件已被包含是否仍然包含(类似php中的include_once函数)
assign | string | No | n/a | 该属性指定一个变量保存待包含php文件的输出

include_php tags are used to include a php script in your template. If security is enabled, then the php script must be located in the $trusted_dir path. The include_php tag must have the attribute "file", which contains the path to the included php file, either relative to $trusted_dir, or an absolute path.

inluce_php 函数用于在模板中包含 php 脚本. 如果设置了安全模式，被包含的脚本必须位于 $trusted_dir 路径下. include_php 函数必须设置 file 属性，该属性指明被包含 php 文件的路径，可以是 $trusted_dir 的相对路径，也可以是绝对路径.

include_php is a nice way to handle componentized templates, and keep PHP code separate from the template files. Lets say you have a template that shows your site navigation, which is pulled dynamically from a database. You can keep your PHP logic that grabs database content in a separate directory, and include it at the top of the template. Now you can include this template anywhere without worrying if the database information was assigned by the application before hand.

include_php 是解决模板部件化的好方法，它使得 php 代码从模板文件中被分离出来. 举个例子：假设有一个从数据库中动态取出数据用于显示站点导航的模板，你可以将得数据内容的 php 逻辑部分分离出来保存在一个单独的文件夹下，并在模板开始的位置包含该 php 脚本. 那么就可以在任何地方包含此模板而不用担心之前数据库信息是否已被程序取出.

By default, php files are only included once even if called multiple times in the template. You can specify that it should be included every time with the once attribute. Setting once to false will include the php script each time it is included in the template.

即使是在模板中多次地调用 php 文件，默认情况下它们只被包含一次. 你可以设置 once 属性从而指明每次调用都重新包含该文件. 如果将 once 属性设置为 false，每次调用该文件都将被重新包含.

You can optionally pass the assign attribute, which will specify a template variable name that the output of include_php will be assigned to instead of displayed.

如果设置了 assign 属性，该属性对应的变量名用于保存待包含 php 的输出，这样待包含 php 文件的输出就不会直接显示了。

The smarty object is available as $this within the PHP script that you include.

在待包含 php 文件中可以通过 $this 访问 smarty 对象.

Example 7-9. function include_php
例 7-9. include_php 函数演示

load_nav.php
-------------

<?php

    // load in variables from a mysql db and assign them to the template
    // 从mysql数据库中取得数据，将数据赋给模板变量
    require_once("MySQL.class.php");
    $sql = new MySQL;
    $sql->query("select * from site_nav_sections order by name",SQL_ALL);
    $this->assign('sections',$sql->record);

?>

index.tpl
---------

{* absolute path, or relative to $trusted_dir *}
{* 绝对路径或 $trusted_dir 的相对路径 *}
{include_php file="/path/to/load_nav.php"}

{foreach item="curr_section" from=$sections}
    <a href="{$curr_section.url}">{$curr_section.name}</a><br>
{/foreach}

Prev | Home | Next
include | Up | insert


insert

Attribute Name | Type | Required | Default | Description
name | string | Yes | n/a | The name of the insert function (insert_name)
assign | string | No | n/a | The name of the template variable the output will be assigned to
script | string | No | n/a | The name of the php script that is included before the insert function is called
[var ...] | [var type] | No | n/a | variable to pass to insert function

属性 | 类型 | 是否必须 | 缺省值 | 描述
name | string | Yes | n/a | 插入函数的名称
assign | string | No | n/a | 该属性指定一个变量保存待插入函数输出
script | string | No | n/a | 插入函数前需要先包含的php脚本名称
[var ...] | [var type] | No | n/a | 传递给待插入函数的本地参数

Insert tags work much like include tags, except that insert tags are not cached when you have template caching enabled. They will be executed on every invocation of the template.

Insert 函数类似欲 inluce 函数，不同之处是 insert 所包含的内容不会被缓存，每次调用该模板都会重新执行该函数.

Let's say you have a template with a banner slot at the top of the page. The banner can contain any mixture of HTML, images, flash, etc. so we can't just use a static link here, and we don't want this contents cached with the page. In comes the insert tag: the template knows #banner_location_id# and #site_id# values (gathered from a config file), and needs to call a function to get the banner contents.

例如你在页面上端使用一个带有广告条位置的模板，广告条可以包含任何HTML、图象、FLASH等混合信息. 因此这里不能使用一个静态的链接，同时我们也不希望该广告条被缓存. 这就需要在 insert 函数指定：#banner_location_id# 和 #site_id# 值(从配置文件中取)，同时需要一个函数取广告条的内容信息.

Example 7-10. function insert
例 7-10. insert 函数演示

{* example of fetching a banner *}
{insert name="getBanner" lid=#banner_location_id# sid=#site_id#}

In this example, we are using the name "getBanner" and passing the parameters #banner_location_id# and #site_id#. Smarty will look for a function named insert_getBanner() in your PHP application, passing the values of #banner_location_id# and #site_id# as the first argument in an associative array. All insert function names in your application must be prepended with "insert_" to remedy possible function name-space conflicts. Your insert_getBanner() function should do something with the passed values and return the results. These results are then displayed in the template in place of the insert tag. In this example, Smarty would call this function: insert_getBanner(array("lid" => "12345","sid" => "67890")); and display the returned results in place of the insert tag.

在此例中，我们使用了 getBanner 作为 name 属性，同时传递了 #banner_location_id# 和 #site_id# 两个参数. 接下来 Smarty 在你的 php 程序中搜索名为 insert_getBanner() 的函数，#banner_location_id# 和 #site_id# 的值被组合成一个数组作为函数的第一个参数传递给该函数. 为了避免函数命名混乱，所有的 insert 函数都必须以 insert_ 开头. 你的 insert_getBanner() 函数根据传递的参数执行并返回执行的结果. 这些结果就显示在模板中调用该函数的位置. 在此例中 Smarty 调用该函数类似insert_getBanner(array("lid"=>"12345","sid"=>67890"));并将返回的结果显示在调用的位置.

If you supply the "assign" attribute, the output of the insert tag will be assigned to this template variable instead of being output to the template. NOTE: assigning the output to a template variable isn't too useful with caching enabled.

如果设置了 assign 属性，该属性对应的变量名用于保存待包含函数的输出，这样待包含函数的输出就不会直接显示了.注意：赋给模板变量的输出信息在缓存的时候同样无效.

If you supply the "script" attribute, this php script will be included (only once) before the insert function is executed. This is the case where the insert function may not exist yet, and a php script must be included first to make it work. The path can be either absolute, or relative to $trusted_dir. When security is enabled, the script must reside in $trusted_dir.

如果指定了 script 属性，在调用函数并执行前将先包含(只包含一次)script指定的 php 脚本. 这是为了防止被调用的函数不存在，先调用包含该函数的 php 脚本将避免该情况.

The Smarty object is passed as the second argument. This way you can reference and modify information in the Smarty object from within the insert function.

Smart 对象作为函数的第二个参数被传递，在待包含函数中可以通过 $this 访问并修改 smarty 对象信息.

Technical Note: It is possible to have portions of the template not cached. If you have caching turned on, insert tags will not be cached. They will run dynamically every time the page is created, even within cached pages. This works good for things like banners, polls, live weather, search results, user feedback areas, etc.

技术要点: 使模板的一部分不被缓存. 如果打开了缓存, insert 函数却不会被缓存，每次调用页面它们都会被动态加载，即使是在缓存页面中. 该特性可以广泛应用于广告条、投票、实时天气预报、搜索结果、反馈信息等区域.

Prev | Home | Next
include_php | Up | if,elseif,else


if,elseif,else

if statements in Smarty have much the same flexibility as php if statements, with a few added features for the template engine. Every if must be paired with an /if . else and elseif are also permitted. "eq", "ne","neq", "gt", "lt", "lte", "le", "gte" "ge","is even","is odd", "is not even","is not odd","not","mod","div by","even by","odd by","==","!=",">", "<","<=",">=" are all valid conditional qualifiers, and must be separated from surrounding elements by spaces.

Smarty 中的 if 语句和 php 中的 if 语句一样灵活易用，并增加了几个特性以适宜模板引擎. if 必须于 /if 成对出现. 可以使用 else 和 elseif 子句. 可以使用以下条件修饰词：eq、ne、neq、gt、lt、lte、le、gte、ge、is even、is odd、is not even、is not odd、not、mod、div by、even by、odd by、==、!=、>、<、<=、>=. 使用这些修饰词时必须和变量或常量用空格格开.

Example 7-11. if statements
例 7-11. if 语句演示

{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}

Prev | Home | Next
insert | Up | ldelim,rdelim


ldelim,rdelim

ldelim and rdelim are used for displaying the literal delimiter, in our case "{" or "}". The template engine always tries to interpret delimiters, so this is the way around that.

ldelim 和 rdelim 用于输出分隔符，也就是大括号 "{" 和 "}". 模板引擎总是尝试解释大括号内的内容，因此如果需要输出大括号，请使用此方法.

Example 7-12. ldelim, rdelim
例 7-12. 使用 ldelim, 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!

Prev | Home | Next
if,elseif,else | Up | literal


literal

Literal tags allow a block of data to be taken literally, not being interpreted by the Smarty engine. This is handy for things like javascript sections, where there maybe curly braces and such things that would confuse the template parser. Anything within {literal}{/literal} tags is not interpreted, but displayed as-is.

Literal 标签区域内的数据将被当作文本处理，此时模板将忽略其内部的所有字符信息. 该特性用于显示有可能包含大括号等字符信息的 javascript 脚本. 当这些信息处于 {literal}{/literal} 标签中时，模板引擎将不分析它们，而直接显示.

Example 7-13. literal tags
例 7-13. literal 标签演示

{literal}
    <script language=javascript>

     <!--
     function isblank(field) {
     if (field.value == '')
     { return false; }
     else
     {
     document.loginform.submit();
     return true;
     }
     }
     // -->

    </script>
{/literal}

Prev | Home | Next
ldelim,rdelim | Up | php


php

php tags allow php to be embedded directly into the template. They will not be escaped, regardless of the $php_handling setting. This is for advanced users only, not normally needed.

php 标签允许在模板中直接嵌入 php 脚本. 是否处理这些语句取决于$php_handling的设置. 该语句通常不需要使用，当然如果你非常了解此特性或认为必须要用，也可以使用.

Example 7-14. php tags
例 7-14. php 标签演示

{php}
        // including a php script directly
        // from the template.
        include("/path/to/display_weather.php");
{/php}

Prev | Home | Next
literal | Up | section,sectionelse


section,sectionelse

Table of Contents目录
index
index_prev
index_next
iteration
first
last
rownum
loop
show
total

Attribute Name | Type | Required | Default | Description
name | string | Yes | n/a | The name of the section
loop | [$variable_name] | Yes | n/a | The name of the variable to determine # of loop iterations
start | integer | No | 0 | The index position that the section will begin looping. If the value is negative, the start position is calculated from the end of the array. For example, if there are seven values in the loop array and start is -2, the start index is 5. Invalid values (values outside of the length of the loop array) are automatically truncated to the closest valid value.
step | integer | No | 1 | The step value that will be used to traverse the loop array. For example, step=2 will loop on index 0,2,4, etc. If step is negative, it will step through the array backwards.
max | integer | No | 1 | Sets the maximum number of times the section will loop.
show | boolean | No | true | determines whether or not to show this section

属性 | 类型 | 是否必须 | 缺省值 | 描述
name | string | Yes | n/a | 该循环的名称
loop | [$variable_name] | Yes | n/a | 决定循环次数的变量名称
start | integer | No | 0 | 循环执行的初始位置. 如果该值为负数，开始位置从数组的尾部算起. 例如：如果数组中有7个元素，指定start为-2，那么指向当前数组的索引为5. 非法值(超过了循环数组的下限)将被自动调整为最接近的合法值.
step | integer | No | 1 | 该值决定循环的步长. 例如指定step=2将只遍历下标为0、2、4等的元素. 如果step为负值，那么遍历数组的时候从后向前遍历.
max | integer | No | 1 | 设定循环最大执行次数.
show | boolean | No | true | 决定是否显示该循环.

Template sections are used for looping over arrays of data. All section tags must be paired with /section tags. Required parameters are name and loop . The name of the section can be anything you like, made up of letters, numbers and underscores. Sections can be nested, and the nested section names must be unique from each other. The loop variable (usually an array of values) determines the number of times the section will loop. When printing a variable within a section, the section name must be given next to variable name within brackets []. sectionelse is executed when there are no values in the loop variable.

模板的 section 用于遍历数组中的数据. section 标签必须成对出现. 必须设置 name 和 loop 属性. 名称可以是包含字母、数字和下划线的任意组合. 可以嵌套但必须保证嵌套的 name 唯一. 变量 loop (通常是数组)决定循环执行的次数. 当需要在 section 循环内输出变量时，必须在变量后加上中括号包含着的 name 变量. sectionelse 当 loop 变量无值时被执行.

Example 7-15. section
例 7-15. section 函数演示

{* this example will print out all the values of the $custid array *}
{section name=customer loop=$custid}
    id: {$custid[customer]}<br>
{/section}

OUTPUT:

id: 1000<br>
id: 1001<br>
id: 1002<br>

Example 7-16. section loop variable
例 7-16.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>

Example 7-17. section names
例 7-17. section 名称演示

{* the name of the section can be anything you like,
 and it is used to reference the data within the section *}
{section name=mydata loop=$custid}
    id: {$custid[mydata]}<br>
    name: {$name[mydata]}<br>
    address: {$address[mydata]}<br>
    <p>
{/section}

Example 7-18. nested sections
例 7-18. 嵌套 section 演示

{* sections can be nested as deep as you like. With nested sections,
 you can access complex data structures, such as multi-dimensional
 arrays. In this example, $contact_type[customer] is an array of
 contact types for the current customer. *}
{section name=customer loop=$custid}
    id: {$custid[customer]}<br>
    name: {$name[customer]}<br>
    address: {$address[customer]}<br>
    {section name=contact loop=$contact_type[customer]}
        {$contact_type[customer][contact]}: {$contact_info[customer][contact]}<br>
    {/section}
    <p>
{/section}

OUTPUT:

id: 1000<br>
name: John Smith<br>
address: 253 N 45th<br>
home phone: 555-555-5555<br>
cell phone: 555-555-5555<br>
e-mail: john@mydomain.com<br>
<p>
id: 1001<br>
name: Jack Jones<br>
address: 417 Mulberry ln<br>
home phone: 555-555-5555<br>
cell phone: 555-555-5555<br>
e-mail: jack@mydomain.com<br>
<p>
id: 1002<br>
name: Jane Munson<br>
address: 5605 apple st<br>
home phone: 555-555-5555<br>
cell phone: 555-555-5555<br>
e-mail: jane@mydomain.com<br>
<p>

Example 7-19. sections and associative arrays
例 7-19. section 遍历多维数组演示

{* This is an example of printing an associative array
 of data within a section *}
{section name=customer loop=$contacts}
    name: {$contacts[customer].name}<br>
    home: {$contacts[customer].home}<br>
    cell: {$contacts[customer].cell}<br>
    e-mail: {$contacts[customer].email}<p>
{/section}

OUTPUT:

name: John Smith<br>
home: 555-555-5555<br>
cell: 555-555-5555<br>
e-mail: john@mydomain.com<p>
name: Jack Jones<br>
home phone: 555-555-5555<br>
cell phone: 555-555-5555<br>
e-mail: jack@mydomain.com<p>
name: Jane Munson<br>
home phone: 555-555-5555<br>
cell phone: 555-555-5555<br>
e-mail: jane@mydomain.com<p>

Example 7-20. sectionelse
例 7-20. sectionelse 演示

{* sectionelse will execute if there are no $custid values *}
{section name=customer loop=$custid}
    id: {$custid[customer]}<br>
{sectionelse}
    there are no values in $custid.
{/section}

Sections also have their own variables that handle section properties. These are indicated like so: {$smarty.section.sectionname.varname}

Section 循环也有可供调用的变量名. 通过如下方式调用{$smarty.section.sectionname.varname}.

NOTE: As of Smarty 1.5.0, the syntax for section property variables has been changed from {%sectionname.varname%} to {$smarty.section.sectionname.varname}. The old syntax is still supported, but you will only see reference to the new syntax in the manual examples.

注意：Smarty 1.5.0 版中，section 名称属性变量的格式由{%sectionname.varname%}变成 {$smarty.section.sectionname.varname}，老版本的格式依然支持，但在手册的例子中只提供新的格式.

Prev | Home | Next
php | Up | index


index

index is used to display the current loop index, starting with zero (or the start attribute if given), and incrementing by one (or by the step attribute if given.)

index 用于显示当前循环的索引，从0开始(如果指定了start属性，那么由该值开始)，每次加1(如果指定了step属性，那么由该值决定).

Technical Note: If the step and start section properties are not modified, then this works the same as the iteration section property, except it starts on 0 instead of 1.

技术细节：如果没有指定step和start属性，此值的作用和iteration类似，只不过从0开始而已.

Example 7-21. section property index
例 7-21. section 的 index 属性演示

    {section name=customer loop=$custid}
    {$smarty.section.customer.index} id: {$custid[customer]}<br>
    {/section}

    OUTPUT:

    0 id: 1000<br>
    1 id: 1001<br>
    2 id: 1002<br>

Prev | Home | Next
section,sectionelse | Up | index_prev


index_prev

index_prev is used to display the previous loop index. on the first loop, this is set to -1.

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

Example 7-22. section property index_prev
例 7-22. section 的 index_prev 属性演示

    {section name=customer loop=$custid}
    {$smarty.section.customer.index} id: {$custid[customer]}<br>
    {* FYI, $custid[customer.index] and $custid[customer] are identical in meaning *}
    {if $custid[customer.index_prev] ne $custid[customer.index]}
     The customer id changed<br>
    {/if}
    {/section}

    OUTPUT:

    0 id: 1000<br>
     The customer id changed<br>
    1 id: 1001<br>
     The customer id changed<br>
    2 id: 1002<br>
     The customer id changed<br>

Prev | Home | Next
index | Up | index_next


index_next

index_next is used to display the next loop index. On the last loop, this is still one more than the current index (respecting the setting of the step attribute, if given.)

index_next 用于显示下一个循环索引值. 循环执行到最后一次时，此值仍然比当前索引值大1(如果指定了step，取决于此值).

Example 7-23. section property index_next
例 7-22. section 的 index_next 属性演示

    {section name=customer loop=$custid}
    {$smarty.section.customer.index} id: {$custid[customer]}<br>
    {* FYI, $custid[customer.index] and $custid[customer] are identical in meaning *}
    {if $custid[customer.index_next] ne $custid[customer.index]}
     The customer id will change<br>
    {/if}
    {/section}

    OUTPUT:

    0 id: 1000<br>
     The customer id will change<br>
    1 id: 1001<br>
     The customer id will change<br>
    2 id: 1002<br>
     The customer id will change<br>

Prev | Home | Next
index_prev | Up | iteration


iteration

iteration is used to display the current loop iteration.

iteration 用于显示循环的次数.

NOTE: This is not affected by the section properties start, step and max, unlike the index property. Iteration also starts with 1 instead of 0 like index. rownum is an alias to iteration, they work identical.

注意：iteration 不像index属性受start、step和max属性的影响，该值总是从1开始(index是从0开始的).rownum 是iteration的别名，两者等同.

Example 7-24. section property iteration
例 7-24. section 的 iteration 属性演示

    {section name=customer loop=$custid start=5 step=2}
    current loop iteration: {$smarty.section.customer.iteration}<br>
    {$smarty.section.customer.index} id: {$custid[customer]}<br>
    {* FYI, $custid[customer.index] and $custid[customer] are identical in meaning *}
    {if $custid[customer.index_next] ne $custid[customer.index]}
     The customer id will change<br>
    {/if}
    {/section}

    OUTPUT:

    current loop iteration: 1
    5 id: 1000<br>
     The customer id will change<br>
    current loop iteration: 2
    7 id: 1001<br>
     The customer id will change<br>
    current loop iteration: 3
    9 id: 1002<br>
     The customer id will change<br>

Prev | Home | Next
index_next | Up | first


first

first is set to true if the current section iteration is the first one.

如果当前循环第一次执行，first 被设置为true.

Example 7-25. section property first
例 7-25. section 的 first 属性演示

    {section name=customer loop=$custid}
    {if $smarty.section.customer.first}
     <table>
    {/if}

    <tr><td>{$smarty.section.customer.index} id:
     {$custid[customer]}</td></tr>

    {if $smarty.section.customer.last}
     </table>
    {/if}
    {/section}

    OUTPUT:

    <table>
    <tr><td>0 id: 1000</td></tr>
    <tr><td>1 id: 1001</td></tr>
    <tr><td>2 id: 1002</td></tr>
    </table>

Prev | Home | Next
iteration | Up | last


last

last is set to true if the current section iteration is the last one.

如果当前循环执行到最后一次，last 被设置为true.

Example 7-26. section property last
例 7-26. section 的 last 属性演示

    {section name=customer loop=$custid}
    {if $smarty.section.customer.first}
     <table>
    {/if}

    <tr><td>{$smarty.section.customer.index} id:
     {$custid[customer]}</td></tr>

    {if $smarty.section.customer.last}
     </table>
    {/if}
    {/section}

    OUTPUT:

    <table>
    <tr><td>0 id: 1000</td></tr>
    <tr><td>1 id: 1001</td></tr>
    <tr><td>2 id: 1002</td></tr>
    </table>

Prev | Home | Next
first | Up | rownum


rownum

rownum is used to display the current loop iteration, starting with one. It is an alias to iteration, they work identically.

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

Example 7-27. section property rownum
例 7-27. section 的 rownum 属性演示

    {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>

Prev | Home | Next
last | Up | loop


loop

loop is used to display the last index number that this section looped. This can be used inside or after the section.

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

Example 7-28. section property index

    {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.

Prev | Home | Next
rownum | Up | show


show

show is used as a parameter to section. show is a boolean value, true or false. If false, the section will not be displayed. If there is a sectionelse present, that will be alternately displayed.

show 是 section 的参数. show 取值为布尔值 true 或 false. 如果设置为 false，该循环将不显示. 如果指定了 sectionelse 子句，该字句是否显示也取决于该值.

Example 7-29. section attribute show
例 7-29. section 的 show 属性演示

    {* $show_customer_info may have been passed from the PHP
    application, to regulate whether or not this section shows *}
    {section name=customer loop=$custid show=$show_customer_info}
    {$smarty.section.customer.rownum} id: {$custid[customer]}<br>
    {/section}

    {if $smarty.section.customer.show}
    the section was shown.
    {else}
    the section was not shown.
    {/if}

    OUTPUT:

    1 id: 1000<br>
    2 id: 1001<br>
    3 id: 1002<br>

    the section was shown.

Prev | Home | Next
loop | Up | total


total

total is used to display the number of iterations that this section will loop. This can be used inside or after the section.

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

Example 7-30. section property total
例 7-30. section 的 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.

Prev | Home | Next
show | Up | strip


strip

Many times web designers run into the issue where white space and carriage returns affect the output of the rendered HTML (browser "features"), so you must run all your tags together in the template to get the desired results. This usually ends up in unreadable or unmanageable templates.

Web 开发者多次遇到空格和回车影响HTML输出的情形(浏览器的"特性")，为了得到特定的结果，因此你不得不在模板里运行所有的标签. 通常在难以理解或难以处理的模板中遇到此问题.

Anything within {strip}{/strip} tags in Smarty are stripped of the extra spaces or carriage returns at the beginnings and ends of the lines before they are displayed. This way you can keep your templates readable, and not worry about extra white space causing problems.

Smarty 在显示前将除区任何位于 {strip}{/strip} 标记中数据的首尾空格和回车. 这样可以保证模板容易理解且不用担心多余的空格导致问题.

Technical Note: {strip}{/strip} does not affect the contents of template variables. See the strip modifier function.

技术要点：

Example 7-31. strip tags
例 7-31. 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>

Notice that in the above example, all the lines begin and end with HTML tags. Be aware that all the lines are run together. If you have plain text at the beginning or end of any line, they will be run together, and may not be desired results.

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

Prev | Home | Next
total | Up | Custom Functions


Custom Functions

Smarty - php 模板编译引擎
Prev Next

Chapter 8. Custom Functions[第八章.自定义函数]

Table of Contents
assign
counter
cycle
debug
eval
fetch
html_checkboxes
html_image
html_options
html_radios
html_select_date
html_select_time
html_table
math
mailto
popup_init
popup
textformat

Smarty comes with several custom functions that you can use in the templates.

用户可以使用 Smarty 自带的一组自定义函数.

assign

Attribute Name | Type | Required | Default | Description
var | string | Yes | n/a | The name of the variable being assigned
value | string | Yes | n/a | The value being assigned

属性 | 类型 | 是否必须 | 缺省值 | 描述
var | string | Yes | n/a | 被赋值的变量名
value | string | Yes | n/a | 赋给变量的值

assign is used for assigning template variables during the execution of the template.

assign 用于在模板被执行时为模板变量赋值.

Example 8-1. assign
例 8-1. assign 函数演示

{assign var="name" value="Bob"}

The value of $name is {$name}.

OUTPUT:

The value of $name is Bob.

Prev | Home | Next
strip | Up | counter


counter

Attribute Name | Type | Required | Default | Description
name | string | No | default | The name of the counter
start | number | No | 1 | The initial number to start counting from
skip | number | No | 1 | The interval to count by
direction | string | No | up | the direction to count (up/down)
print | boolean | No | true | Whether or not to print the value
assign | string | No | n/a | the template variable the output will be assigned to

属性 | 类型 | 是否必须 | 缺省值 | 描述
name | string | No | default | 计数器的名称
start | number | No | 1 | 记数器初始值
skip | number | No | 1 | 记数器间隔、步长
direction | string | No | up | 记数器方向，(增/减)
print | boolean | No | true | 是否输出值
assign | string | No | n/a | 输出值将被赋给模板变量的名称

counter is used to print out a count. counter will remember the count on each iteration. You can adjust the number, the interval and the direction of the count, as well as determine whether or not to print the value. You can run multiple counters concurrently by supplying a unique name for each one. If you do not supply a name, the name 'default' will be used.

counter 用于输出一个记数过程. counter 保存了每次记数时的当前记数值. 用户可以通过调节 interval 和 direction 调节该值. 也可以决定是否输出该值. 如果需要同时运行多个计数器，必须为它们指定不同的名称. 如果没有指定名称，模板引擎使用 "default" 作为缺省值.

If you supply the special "assign" attribute, the output of the counter function will be assigned to this template variable instead of being output to the template.

如果指定了 "assign" 这个特殊属性，该计数器的输出值将被赋给由 assign 指定的模板变量，而不是直接输出.

Example 8-2. counter
例 8-2. counter 函数演示

{* initialize the count *}
{counter start=0 skip=2 print=false}

{counter}<br>
{counter}<br>
{counter}<br>
{counter}<br>

OUTPUT:

2<br>
4<br>
6<br>
8<br>

Prev | Home | Next
Custom Functions | Up | cycle


cycle

Attribute Name | Type | Required | Default | Description
name | string | No | default | The name of the cycle
values | mixed | Yes | N/A | The values to cycle through, either a comma delimited list (see delimiter attribute), or an array of values.
print | boolean | No | true | Whether to print the value or not
advance | boolean | No | true | Whether or not to advance to the next value
delimiter | string | No | , | The delimiter to use in the values attribute.
assign | string | No | n/a | the template variable the output will be assigned to

属性 | 类型 | 是否必须 | 缺省值 | 描述
name | string | No | default | 轮转的名称
values | mixed | Yes | N/A | 待轮转的值，可以是用逗号分隔的列表(请查看 delimiter 属性)或一个包含多值的数组.
print | boolean | No | true | 是否输出值
advance | boolean | No | true | 是否使用下一个值(为 false 时使用当前值)
delimiter | string | No | , | 指出values 属性中使用的分隔符，默认是逗号.
assign | string | No | n/a | 输出值将被赋给模板变量的名称

Cycle is used to cycle though a set of values. This makes it easy to alternate between two or more colors in a table, or cycle through an array of values.

Cycle 用于轮转使用一组值. 该特性使得在表格中交替输出颜色或轮转使用数组中的值变得很容易.

You can cycle through more than one set of values in your template by supplying a name attribute. Give each set of values a unique name.

如果需要在模板中使用多个轮转，需要给出唯一的 name 属性.

You can force the current value not to print with the print attribute set to false. This would be useful for silently skipping a value.

用户可以设置 print 属性为 false 强制不输出当前值. 该特性可以很方便地略过某个值.

The advance attribute is used to repeat a value. When set to false, the next call to cycle will print the same value.

advance 属性用于重复使用某个值. 当该属性设置为 false 时，下次调用该轮转时将输出同样的值.

If you supply the special "assign" attribute, the output of the cycle function will be assigned to this template variable instead of being output to the template.

如果指定了 "assign" 这个特殊属性，该轮转的输出值将被赋给由 assign 指定的模板变量，而不是直接输出.

Example 8-3. cycle
例 8-3. cycle 函数演示

{section name=rows loop=$data}
<tr bgcolor="{cycle values="#eeeeee,#d0d0d0"}">
 <td>{$data[rows]}</td>
</tr>
{/section}

OUTPUT:

<tr bgcolor="#eeeeee">
 <td>1</td>
</tr>
<tr bgcolor="#d0d0d0">
 <td>2</td>
</tr>
<tr bgcolor="#eeeeee">
 <td>3</td>
</tr>

Prev | Home | Next
counter | Up | debug


debug

Attribute Name | Type | Required | Default | Description
output | string | No | html | output type, html or javascript

属性 | 类型 | 是否必须 | 缺省值 | 描述
output | string | No | html | 输出类型，html或javascript

{debug} dumps the debug console to the page. This works regardless of the debug settings in Smarty. Since this gets executed at runtime, this is only able to show the assigned variables, not the templates that are in use. But, you see all the currently available variables within the scope of this template.

{debug} 将调式信息输出到页面上. 该函数是否可用取决于 Smarty 的 debug 设置. 该函数在运行时取得数据，因此不能显示使用中的模板，只能显示运行时被赋值的变量. 不过还是可以看到所有模板内当前可用的变量.

Prev | Home | Next
cycle | Up | eval


eval

Attribute Name | Type | Required | Default | Description
var | mixed | Yes | n/a | variable (or string) to evaluate
assign | string | No | n/a | the template variable the output will be assigned to

属性 | 类型 | 是否必须 | 缺省值 | 描述
var | mixed | Yes | n/a | 待求值的变量(或字符串)
assign | string | No | n/a | 输出值将被赋给模板变量的名称

eval is used to evaluate a variable as a template. This can be used for things like embedding template tags/variables into variables or tags/variables into config file variables.

eval 按处理模板的方式计算取得变量的值. 该特性可用于在配置文件中的标签/变量中嵌入其它模板标签/变量.

If you supply the special "assign" attribute, the output of the eval function will be assigned to this template variable instead of being output to the template.

如果指定了 "assign" 这个特殊属性，该函数的输出值将被赋给由 assign 指定的模板变量，而不是直接输出.

Technical Note: Evaluated variables are treated the same as templates. They follow the same escapement and security features just as if they were templates.

技术要点: 待求值处理的变量被当作模板来处理. 它们和模板一样遵循同样的结构和安全特性.

Technical Note: Evaluated variables are compiled on every invocation, the compiled versions are not saved! However if you have caching enabled, the output will be cached with the rest of the template.

技术要点: 待求值处理的变量每次调用时被重编译，不保存编译版本! 但当打开缓冲设置时，该输出会被其它模板缓冲.

Example 8-4. eval
例 8-4. eval 函数演示

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>.
Prev | Home | Next
debug | Up | fetch


fetch

Attribute Name | Type | Required | Default | Description
file | string | Yes | n/a | the file, http or ftp site to fetch
assign | string | No | n/a | the template variable the output will be assigned to

属性 | 类型 | 是否必须 | 缺省值 | 描述
file | string | Yes | n/a | 待请求的文件，http或ftp方式.
assign | string | No | n/a | 输出值将被赋给模板变量的名称

fetch is used to fetch files from the local file system, http, or ftp and display the contents. If the file name begins with "http://", the web site page will be fetched and displayed. If the file name begins with "ftp://", the file will be fetched from the ftp server and displayed. For local files, the full system file path must be given, or a path relative to the executed php script.

fetch 用于从本地文件系统、HTTP或FTP上取得文件并显示文件的内容. 如果文件名称以"http://"开头，将取得该网站页面并显示. 如果文件名称以"ftp://"开头，将从ftp服务器取得该文件并显示.

If you supply the special "assign" attribute, the output of the fetch function will be assigned to this template variable instead of being output to the template. (new in Smarty 1.5.0)

如果指定了 "assign" 这个特殊属性，该函数的输出值将被赋给由 assign 指定的模板变量，而不是直接输出.(Smarty 版本 1.5.0 新特性)

Technical Note: This will not support http redirects, be sure to include a trailing slash on your web page fetches where necessary.

技术要点: 该函数不支持HTTP重定向，如果要取得web默认页，比如想取得www.domain.com的主页资料，但是不知道主页的具体名称，可能是index.php或index.htm或default.php等等，可以直接使用该站点的url，记得在url结尾处加上反斜线.

Technical Note: If template security is turned on and you are fetching a file from the local file system, this will only allow files from within one of the defined secure directories. ($secure_dir)

技术要点: 如果模板的安全设置打开了，当取本地文件时只能取位于定义为安全文件夹下的资料. ($secure_dir)

Example 8-5. fetch
例 8-5. fetch 函数演示

{* include some javascript in your template *}
{fetch file="/export/httpd/www.domain.com/docs/navbar.js"}

{* embed some weather text in your template from another web site *}
{fetch file="http://www.myweather.com/68502/"}

{* fetch a news headline file via ftp *}
{fetch file="ftp://user:password@ftp.domain.com/path/to/currentheadlines.txt"}

{* assign the fetched contents to a template variable *}
{fetch file="http://www.myweather.com/68502/" assign="weather"}
{if $weather ne ""}
    <b>{$weather}</b>
{/if}

Prev | Home | Next
eval | Up | html_checkboxes


html_checkboxes

Attribute Name | Type | Required | Default | Description
name | string | No | checkbox | name of checkbox list
values | array | Yes, unless using options attribute | n/a | an array of values for checkbox buttons
output | array | Yes, unless using options attribute | n/a | an array of output for checkbox buttons
selected | string/array | No | empty | the checked checkbox element(s)
options | associative array | Yes, unless using values and output | n/a | an associative array of values and output
separator | string | No | empty | string of text to separate each checkbox item
labels | boolean | No | true | add <label>-tags to the output

属性 | 类型 | 是否必须 | 缺省值 | 描述
name | string | No | checkbox | 复选按钮组的名称
values | array | Yes, 或指定 options 属性 | n/a | 包含复选按钮组值的数组
output | array | Yes, 或指定 options 属性 | n/a | 包含复选按钮组显示值的数组
selected | string/array | No | empty | 已选定的元素或元素数组
options | associative array | Yes,或指定 values 属性 | n/a | 包含值和显示的关联数组
separator | string | No | empty | 分隔每个复选按钮的字符串
labels | boolean | No | true | 是否为每个复选按钮添加 <label> 标签

html_checkboxes is a custom function that creates an html checkbox group with provided data. It takes care of which item(s) are selected by default as well. Required attributes are values and output, unless you use options instead. All output is XHTML compatible.

自定义函数 html_checkboxes 根据给定的数据创建复选按钮组. 该函数可以指定哪些元素被选定. 要么必须指定 values 和 ouput 属性，要么指定 options 替代. 所有的输出与 XHTML 兼容.

All parameters that are not in the list above are printed as name/value-pairs inside each of the created <input>-tags.

上表未提到的其它参数在 <input> 标签中以"名称/属性"对的方式显示.

Example 8-6. html_checkboxes
例 8-6. html_checkboxes 函数演示

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('cust_ids', array(1000,1001,1002,1003));
$smarty->assign('cust_names', array('Joe Schmoe','Jack Smith','Jane Johnson','Charlie Brown'));
$smarty->assign('customer_id', 1001);
$smarty->display('index.tpl');

index.tpl:

{html_checkboxes values=$cust_ids checked=$customer_id output=$cust_names separator="<br />"}

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('cust_checkboxes', array(
            1000 => 'Joe Schmoe',
            1001 => 'Jack Smith',
            1002 => 'Jane Johnson',
            1003 => 'Charlie Brown'));
$smarty->assign('customer_id', 1001);
$smarty->display('index.tpl');

index.tpl:

{html_checkboxes name="id" options=$cust_checkboxes checked=$customer_id separator="<br />"}

OUTPUT: (both examples)

<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 />

Prev | Home | Next
fetch | Up | html_image


html_image

Attribute Name | Type | Required | Default | Description
file | string | Yes | n/a | name/path to image
border | string | No | 0 | size of border around image
height | string | No | actual image height | height to display image
width | string | No | actual image width | width to display image
basedir | string | no | web server doc root | directory to base relative paths from
alt | string | no | "" | alternative description of the image
href | string | no | n/a | href value to link the image to

属性 | 类型 | 是否必须 | 缺省值 | 描述
file | string | Yes | n/a | 图象文件的名称或路径
border | string | No | 0 | 图象边框大小
height | string | No | actual image height | 显示图象高度
width | string | No | actual image width | 显示图象宽度
basedir | string | no | web server doc root | 图象文件位置的相对路径
alt | string | no | "" | 可选图象描述(鼠标指向图象或图象文件不存在时显示的字符串信息)
href | string | no | n/a | 图象链接到的地址

html_image is a custom function that generates an HTML tag for an image. The height and width are automatically calculated from the image file if none are supplied.

自定义函数 html_image 产生一个图象的 HTML 标签. 如果没有提供高度和宽度值，将根据图象的实际大小自动取得.

basedir is the base directory that relative image paths are based from. If not given, the web server document root (env variable DOCUMENT_ROOT) is used as the base. If security is enabled, the path to the image must be within a secure directory.

basedir 是相对图象路径的基路径. 如果没有给出该属性，将依据WEB服务器的根路径(环境变量 DOCUMENT_ROOT)为准. 如果模板的安全设置打开了，图象的位置必须位于为安全文件夹下.

href is the href value to link the image to. If link is supplied, an <a href="LINKVALUE"><a> tag is put around the image tag.

href 是图象链接指向的位置. 如果设置了该属性，图象两侧将被加上超级链接标签，形成一个图象链接.

Technical Note: html_image requires a hit to the disk to read the image and calculate the height and width. If you don't use template caching, it is generally better to avoid html_image and leave image tags static for optimal performance.

技术要点: html_image 需要访问磁盘以获取图象的尺寸. 如果不使用缓冲，为了优化性能，一般情况下建议使用静态图象标签而避免使用 html_iamge.

Example 8-7. html_image
例 8-7. html_image 函数演示

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->display('index.tpl');

index.tpl:

{html_image file="pumpkin.jpg"}
{html_image file="/path/from/docroot/pumpkin.jpg"}
{html_image file="../path/relative/to/currdir/pumpkin.jpg"}

OUTPUT: (possible)

<img src="pumpkin.jpg" alt="" border="0" width="44" height="68" />
<img src="/path/from/docroot/pumpkin.jpg" alt="" border="0" width="44" height="68" />
<img src="../path/relative/to/currdir/pumpkin.jpg" alt="" border="0" width="44" height="68" />

Prev | Home | Next
html_checkboxes | Up | html_options


html_options

Attribute Name | Type | Required | Default | Description
values | array | Yes, unless using options attribute | n/a | an array of values for dropdown
output | array | Yes, unless using options attribute | n/a | an array of output for dropdown
selected | string/array | No | empty | the selected option element(s)
options | associative array | Yes, unless using values and output | n/a | an associative array of values and output
name | string | No | empty | name of select group

属性 | 类型 | 是否必须 | 缺省值 | 描述
values | array | Yes, unless using options attribute | n/a | 包含下拉列表各元素值的数组
output | array | Yes, unless using options attribute | n/a | 包含下拉列表各元素显示值的数组
selected | string/array | No | empty | 已选定的元素或元素数组
options | associative array | Yes, unless using values and output | n/a | 包含值和显示的关联数组
name | string | No | empty | 下拉菜单的名称

html_options is a custom function that creates html option group with provided data. It takes care of which item(s) are selected by default as well. Required attributes are values and output, unless you use options instead.

自定义函数 html_options 根据给定的数据创建选项组. 该函数可以指定哪些元素被选定. 要么必须指定 values 和 ouput 属性，要么指定 options 替代.

If a given value is an array, it will treat it as an html OPTGROUP, and display the groups. Recursion is supported with OPTGROUP. All output is XHTML compatible.

如果给定值是数组，将作为 OPTGROUP 处理，且支持递归. 所有的输出与 XHTML 兼容.

If the optional name attribute is given, the <select name="groupname"></select> tags will enclose the option list. Otherwise only the option list is generated.

如果指定了可选属性 name，该选项列表将将被置于<select name="groupname"></select>标签对中. 如果没有指定，那么只产生选项列表.

All parameters that are not in the list above are printed as name/value-pairs inside the <select>-tag. They are ignored if the optional name is not given.

上表未提到的其它参数在 <select> 标签中以"名称/属性"对的方式显示. 如果没有指定可选属性 name 这些参数将被忽略.

Example 8-8. html_options
例 8-8. html_options 函数演示

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('cust_ids', array(1000,1001,1002,1003));
$smarty->assign('cust_names', array('Joe Schmoe','Jack Smith','Jane
Johnson','Carlie Brown'));
$smarty->assign('customer_id', 1001);
$smarty->display('index.tpl');

index.tpl:

<select name=customer_id>
    {html_options values=$cust_ids selected=$customer_id output=$cust_names}
</select>

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('cust_options', array(
            1001 => 'Joe Schmoe',
            1002 => 'Jack Smith',
            1003 => 'Jane Johnson',
            1004 => 'Charlie Brown'));
$smarty->assign('customer_id', 1001);
$smarty->display('index.tpl');

index.tpl:

<select name=customer_id>
    {html_options options=$cust_options selected=$customer_id}
</select>

OUTPUT: (both examples)

<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>

Prev | Home | Next
html_image | Up | html_radios


html_radios

Attribute Name | Type | Required | Default | Description
name | string | No | radio | name of radio list
values | array | Yes, unless using options attribute | n/a | an array of values for radio buttons
output | array | Yes, unless using options attribute | n/a | an array of output for radio buttons
checked | string | No | empty | the checked radio element
options | associative array | Yes, unless using values and output | n/a | an associative array of values and output
separator | string | No | empty | string of text to separate each radio item

属性 | 类型 | 是否必须 | 缺省值 | 描述
name | string | No | radio | 单选按钮列表的名称
values | array | Yes, 或指定 options 属性 | n/a | 包含单选按钮值的数组
output | array | Yes, 或指定 options 属性 | n/a | 包含单选按钮显示值的数组
checked | string | No | empty | 已选定的元素
options | associative array | Yes, 或指定 values 属性 | n/a | 包含值和显示的关联数组
separator | string | No | empty | 分隔每个单选按钮的字符串

html_radios is a custom function that creates html radio button group with provided data. It takes care of which item is selected by default as well. Required attributes are values and output, unless you use options instead. All output is XHTML compatible.

自定义函数 html_radios 根据给定的数据创建单选按钮组. 该函数可以指定哪个元素被选定. 要么必须指定 values 和 ouput 属性，要么指定 options 替代. 所有的输出与 XHTML 兼容.

All parameters that are not in the list above are printed as name/value-pairs inside each of the created <input>-tags.

上表未提到的其它参数在 <input> 标签中以"名称/属性"对的方式显示.

Example 8-9. html_radios
例 8-9. html_radios 函数演示

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('cust_ids', array(1000,1001,1002,1003));
$smarty->assign('cust_names', array('Joe Schmoe','Jack Smith','Jane
Johnson','Carlie Brown'));
$smarty->assign('customer_id', 1001);
$smarty->display('index.tpl');

index.tpl:

{html_radios values=$cust_ids checked=$customer_id output=$cust_names separator="<br />"}

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('cust_radios', array(
            1001 => 'Joe Schmoe',
            1002 => 'Jack Smith',
            1003 => 'Jane Johnson',
            1004 => 'Charlie Brown'));
$smarty->assign('customer_id', 1001);
$smarty->display('index.tpl');

index.tpl:

{html_radios name="id" options=$cust_radios checked=$customer_id separator="<br />"}

OUTPUT: (both examples)

<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 />

Prev | Home | Next
html_options | Up | html_select_date


html_select_date

Attribute Name | Type | Required | Default | Description
prefix | string | No | Date_ | what to prefix the var name with
time | timestamp/YYYY-MM-DD | No | current time in unix timestamp or YYYY-MM-DD format | what date/time to use
start_year | string | No | current year | the first year in the dropdown, either year number, or relative to current year (+/- N)
end_year | string | No | same as start_year | the last year in the dropdown, either year number, or relative to current year (+/- N)
display_days | boolean | No | true | whether to display days or not
display_months | boolean | No | true | whether to display months or not
display_years | boolean | No | true | whether to display years or not
month_format | string | No | %B | what format the month should be in (strftime)
day_format | string | No | %02d | what format the day output should be in (sprintf)
day_value_format | string | No | %d | what format the day value should be in (sprintf)
year_as_text | boolean | No | false | whether or not to display the year as text
reverse_years | boolean | No | false | display years in reverse order
field_array | string | No | null | if a name is given, the select boxes will be drawn such that the results will be returned to PHP in the form of name[Day], name[Year], name[Month].
day_size | string | No | null | adds size attribute to select tag if given
month_size | string | No | null | adds size attribute to select tag if given
year_size | string | No | null | adds size attribute to select tag if given
all_extra | string | No | null | adds extra attributes to all select/input tags if given
day_extra | string | No | null | adds extra attributes to select/input tags if given
month_extra | string | No | null | adds extra attributes to select/input tags if given
year_extra | string | No | null | adds extra attributes to select/input tags if given
field_order | string | No | MDY | the order in which to display the fields
field_separator | string | No | \n | string printed between different fields
month_value_format | string | No | %m | strftime format of the month values, default is %m for month numbers.

属性 | 类型 | 是否必须 | 缺省值 | 描述
prefix | string | No | Date_ | 变量名称前缀
time | timestamp/YYYY-MM-DD | No | UNIX时间戳或年-月-日 | 使用时间类型(data/time)
start_year | string | No | 年份或与当前年份的相对值 | 下拉列表中第一个年份，或与当前年份的相对值(正/负 几年)
end_year | string | No | 同start_year | 下拉列表中最后一个年份，或与当前年份的相对值(正/负 几年)
display_days | boolean | No | true | 是否显示天
display_months | boolean | No | true | 是否显示月
display_years | boolean | No | true | 是否显示年
month_format | string | No | %B | 月份的表示方法(strftime)
day_format | string | No | %02d | 天显示的格式(sprintf)
day_value_format | string | No | %d | 天的表示方法(sprintf)
year_as_text | boolean | No | false | 是否以文本方式显示年份
reverse_years | boolean | No | false | 逆序显示年份
field_array | string | No | null | 如果指定了名称，选定的区域将以[Day],[Year],[Month]的形式返回给PHP(待考)
day_size | string | No | null | 如果给定，为标签添加大小属性
month_size | string | No | null | 如果给定，为标签添加大小属性
year_size | string | No | null | 如果给定，为标签添加大小属性
all_extra | string | No | null | 如果给定，为所有标签添加附加属性
day_extra | string | No | null | 如果给定，为标签添加附加属性
month_extra | string | No | null | 如果给定，为标签添加附加属性
year_extra | string | No | null | 如果给定，为标签添加附加属性
field_order | string | No | MDY | 显示区域的顺序
field_separator | string | No | \n | 各区域间输出的分隔字符串
month_value_format | string | No | %m | 月份值的strftime表示方法，默认为 %m

html_select_date is a custom function that creates date dropdowns for you. It can display any or all of year, month, and day.

自定义函数 html_select_date 用于创建日期下拉菜单. 它可以显示任意年月日.

Example 8-10. html_select_date
例 8-10. html_select_date 函数演示

{html_select_date}

OUTPUT:

<select name="Date_Month">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12" selected>December</option>
</select>
<select name="Date_Day">
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
<option value="4">04</option>
<option value="5">05</option>
<option value="6">06</option>
<option value="7">07</option>
<option value="8">08</option>
<option value="9">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13" selected>13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="Date_Year">
<option value="2001" selected>2001</option>
</select>

Example 8-11. html_select_date
例 8-11. html_select_date 函数演示

{* start and end year can be relative to current year *}
{html_select_date prefix="StartDate" time=$time start_year="-5" end_year="+1" display_days=false}

OUTPUT: (current year is 2000)

<select name="StartDateMonth">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12" selected>December</option>
</select>
<select name="StartDateYear">
<option value="1999">1995</option>
<option value="1999">1996</option>
<option value="1999">1997</option>
<option value="1999">1998</option>
<option value="1999">1999</option>
<option value="2000" selected>2000</option>
<option value="2001">2001</option>
</select>

Prev | Home | Next
html_radios | Up | html_select_time


html_select_time

Attribute Name | Type | Required | Default | Description
prefix | string | No | Time_ | what to prefix the var name with
time | timestamp | No | current time | what date/time to use
display_hours | boolean | No | true | whether or not to display hours
display_minutes | boolean | No | true | whether or not to display minutes
display_seconds | boolean | No | true | whether or not to display seconds
display_meridian | boolean | No | true | whether or not to display meridian (am/pm)
use_24_hours | boolean | No | true | whether or not to use 24 hour clock
minute_interval | integer | No | 1 | number interval in minute dropdown
second_interval | integer | No | 1 | number interval in second dropdown
field_array | string | No | n/a | outputs values to array of this name
all_extra | string | No | null | adds extra attributes to select/input tags if given
hour_extra | string | No | null | adds extra attributes to select/input tags if given
minute_extra | string | No | null | adds extra attributes to select/input tags if given
second_extra | string | No | null | adds extra attributes to select/input tags if given
meridian_extra | string | No | null | adds extra attributes to select/input tags if given

属性 | 类型 | 是否必须 | 缺省值 | 描述
prefix | string | No | Time_ | 变量名称前缀
time | timestamp | No | UNIX时间戳或年-月-日 | 使用时间类型(data/time)
display_hours | boolean | No | true | 是否显示小时
display_minutes | boolean | No | true | 是否显示分钟
display_seconds | boolean | No | true | 是否显示秒
display_meridian | boolean | No | true | 是否显示正午界(上午/下午)
use_24_hours | boolean | No | true | 是否使用24小时制
minute_interval | integer | No | 1 | 分钟下拉列表的间隔
second_interval | integer | No | 1 | 秒钟下拉列表的间隔
field_array | string | No | n/a | 输出值到该值指定的数组
all_extra | string | No | null | 如果给定，为标签添加附加属性
hour_extra | string | No | null | 如果给定，为标签添加附加属性
minute_extra | string | No | null | 如果给定，为标签添加附加属性
second_extra | string | No | null | 如果给定，为标签添加附加属性
meridian_extra | string | No | null | 如果给定，为标签添加附加属性

html_select_time is a custom function that creates time dropdowns for you. It can display any or all of hour, minute, second and meridian.

自定义函数 html_select_time 用于创建时间下拉菜单. 它可以显示任意时分秒.

Example 8-12. html_select_time
例 8-12. html_select_time 函数演示

{html_select_time use_24_hours=true}

OUTPUT:

<select name="Time_Hour">
<option value="00">00</option>
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09" selected>09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
<select name="Time_Minute">
<option value="00">00</option>
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20" selected>20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
<option value="32">32</option>
<option value="33">33</option>
<option value="34">34</option>
<option value="35">35</option>
<option value="36">36</option>
<option value="37">37</option>
<option value="38">38</option>
<option value="39">39</option>
<option value="40">40</option>
<option value="41">41</option>
<option value="42">42</option>
<option value="43">43</option>
<option value="44">44</option>
<option value="45">45</option>
<option value="46">46</option>
<option value="47">47</option>
<option value="48">48</option>
<option value="49">49</option>
<option value="50">50</option>
<option value="51">51</option>
<option value="52">52</option>
<option value="53">53</option>
<option value="54">54</option>
<option value="55">55</option>
<option value="56">56</option>
<option value="57">57</option>
<option value="58">58</option>
<option value="59">59</option>
</select>
<select name="Time_Second">
<option value="00">00</option>
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23" selected>23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
<option value="32">32</option>
<option value="33">33</option>
<option value="34">34</option>
<option value="35">35</option>
<option value="36">36</option>
<option value="37">37</option>
<option value="38">38</option>
<option value="39">39</option>
<option value="40">40</option>
<option value="41">41</option>
<option value="42">42</option>
<option value="43">43</option>
<option value="44">44</option>
<option value="45">45</option>
<option value="46">46</option>
<option value="47">47</option>
<option value="48">48</option>
<option value="49">49</option>
<option value="50">50</option>
<option value="51">51</option>
<option value="52">52</option>
<option value="53">53</option>
<option value="54">54</option>
<option value="55">55</option>
<option value="56">56</option>
<option value="57">57</option>
<option value="58">58</option>
<option value="59">59</option>
</select>
<select name="Time_Meridian">
<option value="am" selected>AM</option>
<option value="pm">PM</option>
</select>

Prev | Home | Next
html_select_date | Up | html_table


html_table

Attribute Name | Type | Required | Default | Description
loop | array | Yes | n/a | array of data to loop through
cols | integer | No | 3 | number of columns in the table
table_attr | string | No | border="1" | attributes for table tag
tr_attr | string | No | empty | attributes for tr tag (arrays are cycled)
td_attr | string | No | empty | attributes for td tag (arrays are cycled)
trailpad | string | No | &nbsp; | value to pad the trailing cells on last row with (if any)
hdir | string | No | right | direction of one row to be rendered. possible values: left / right
vdir | string | No | down | direction of the columns to be rendered. possible values: up / down

属性 | 类型 | 是否必须 | 缺省值 | 描述
loop | array | Yes | n/a | 待遍历的数组
cols | integer | No | 3 | 表格的列数目
table_attr | string | No | border="1" | 表格的属性
tr_attr | string | No | empty | 行标签属性(或轮转数组)
td_attr | string | No | empty | 列标签属性(或轮转数组)
trailpad | string | No | &nbsp; | 最后一行附加的数据(如果有的话)
hdir | string | No | right | 行的对齐方式，可能的值为 left 或 right
vdir | string | No | down | 列的对齐方式，可能的值为 up 或 down

html_table is a custom function that dumps an array of data into an HTML table. The cols attribute determines how many columns will be in the table. The table_attr , tr_attr and td_attr values determine the attributes given to the table, tr and td tags. If tr_attr or td_attr are arrays, they will be cycled through. trailpad is the value put into the trailing cells on the last table row if there are any present.

自定义函数 html_table 将数组中的数据填充到 HTML 表格中. cols 属性决定表格有多少列. table_attr , tr_attr 和 td_attr 属性决定表格中 tr 和 td 标签的一些附加属性. 如果 tr_attr 和 td_attr 属性值为数组，将轮流使用其中的值. 如果指定了 trailpad 属性，将在表尾最后一行附加一些数据.

Example 8-13. html_table
例 8-13. html_table 函数演示

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('data',array(1,2,3,4,5,6,7,8,9));
$smarty->assign('tr',array('bgcolor="#eeeeee"','bgcolor="#dddddd"'));
$smarty->display('index.tpl');

index.tpl:

{html_table loop=$data}
{html_table loop=$data cols=4 table_attr='border="0"'}
{html_table loop=$data cols=4 tr_attr=$tr}

OUTPUT:

<table border="1">
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>4</td><td>5</td><td>6</td></tr>
<tr><td>7</td><td>8</td><td>9</td></tr>
</table>
<table border="0">
<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>
<table border="1">
<tr bgcolor="#eeeeee"><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr bgcolor="#dddddd"><td>5</td><td>6</td><td>7</td><td>8</td></tr>
<tr bgcolor="#eeeeee"><td>9</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
</table>

Prev | Home | Next
html_select_time | Up | math


math

Attribute Name | Type | Required | Default | Description
equation | string | Yes | n/a | the equation to execute
format | string | No | n/a | the format of the result (sprintf)
var | numeric | Yes | n/a | equation variable value
assign | string | No | n/a | template variable the output will be assigned to
[var ...] | numeric | Yes | n/a | equation variable value

属性 | 类型 | 是否必须 | 缺省值 | 描述
equation | string | Yes | n/a | 待执行的表达式
format | string | No | n/a | 结果的格式(遵从sprintf函数)
var | numeric | Yes | n/a | 表达式变量值
assign | string | No | n/a | 输出值将被赋给模板变量的名称
[var ...] | numeric | Yes | n/a | 表达式变量值

math allows the template designer to do math equations in the template. Any numeric template variables may be used in the equations, and the result is printed in place of the tag. The variables used in the equation are passed as parameters, which can be template variables or static values. +, -, /, *, abs, ceil, cos, exp, floor, log, log10, max, min, pi, pow, rand, round, sin, sqrt, srans and tan are all valid operators. Check the PHP documentation for further information on these math functions.

math 允许模板设计者在模板中进行数学表达式运算. 均表达式中可以使用任何数值类型的变量，结果在 math 标签的位置输出. 表达式中使用的变量被当做参数传递给函数，可以是模板变量或静态值. 目前可以使用的运算符有:+, -, /, *, abs, ceil, cos, exp, floor, log, log10, max, min, pi, pow, rand, round, sin, sqrt, srans 和 tan .关于数学函数的详细信息，请查看 PHP 文档.

If you supply the special "assign" attribute, the output of the math function will be assigned to this template variable instead of being output to the template.

如果指定了 "assign" 这个特殊属性，该函数的输出值将被赋给由 assign 指定的模板变量，而不是直接输出.

Technical Note: math is an expensive function in performance due to its use of the php eval() function. Doing the math in PHP is much more efficient, so whenever possible do the math calculations in PHP and assign the results to the template. Definately avoid repetitive math function calls, like within section loops.

技术要点: 由于使用了 php 的 eval() 函数，math 函数的执行效率不高. 在 PHP 中做数学运算效率会更高一些，因此要尽可能在 PHP 中做数学运算，将结果赋给模板变量. 类似在 section 循环，应明确避免反复调用 math 函数.

Example 8-14. math
例 8-14. math 函数演示

{* $height=4, $width=5 *}

{math equation="x + y" x=$height y=$width}

OUTPUT:

9

{* $row_height = 10, $row_width = 20, #col_div# = 2, assigned in template *}

{math equation="height * width / division"
 height=$row_height
 width=$row_width
 division=#col_div#}

OUTPUT:

100

{* you can use parenthesis *}

{math equation="(( x + y ) / z )" x=2 y=10 z=2}

OUTPUT:

6

{* you can supply a format parameter in sprintf format *}

{math equation="x + y" x=4.4444 y=5.0000 format="%.2f"}

OUTPUT:

9.44

Prev | Home | Next
html_table | Up | mailto


mailto

Attribute Name | Type | Required | Default | Description
address | string | Yes | n/a | the e-mail address
text | string | No | n/a | the text to display, default is the e-mail address
encode | string | No | none | How to encode the e-mail. Can be one of none, hex or javascript.
cc | string | No | n/a | e-mail addresses to carbon copy. Separate entries by a comma.
bcc | string | No | n/a | e-mail addresses to blind carbon copy. Separate entries by a comma.
subject | string | No | n/a | e-mail subject.
newsgroups | string | No | n/a | newsgroups to post to. Separate entries by a comma.
followupto | string | No | n/a | addresses to follow up to. Separate entries by a comma.
extra | string | No | n/a | any extra information you want passed to the link, such as style sheet classes

属性 | 类型 | 是否必须 | 缺省值 | 描述
address | string | Yes | n/a | 电子邮件地址
text | string | No | n/a | 邮件链接上显示的文本，默认为电子邮件地址
encode | string | No | none | 编码方式，可选值为 none，hex或javascript
cc | string | No | n/a | 邮件抄送地址，多条地址信息以逗号分隔
bcc | string | No | n/a | 邮件暗送地址，多条地址信息以逗号分隔
subject | string | No | n/a | 邮件主题
newsgroups | string | No | n/a | 发送到新闻组的地址，多条地址信息以逗号分隔
followupto | string | No | n/a | 追踪地址信息，多条信息以逗号分隔
extra | string | No | n/a | 其它需要传递给链接的信息，如css样式

mailto automates the creation of mailto links and optionally encodes them. Encoding e-mails makes it more difficult for web spiders to pick up e-mail addresses off of your site.

mailto 自动生成电子邮件链接，并根据选项决定是否对地址信息编码. 电子邮件地址编码使得网络嗅探程序难以收集到电子邮件地址信息.

Technical Note: javascript is probably the most thorough form of encoding, although you can use hex encoding too.

技术要点: 尽管可以使用 hex 进制编码，但 javascript 已经算得上是很彻底的编码形式了.

Example 8-15. mailto
例 8-15. mailto 函数演示

{mailto address="me@domain.com"}
{mailto address="me@domain.com" text="send me some mail"}
{mailto address="me@domain.com" encode="javascript"}
{mailto address="me@domain.com" encode="hex"}
{mailto address="me@domain.com" subject="Hello to you!"}
{mailto address="me@domain.com" cc="you@domain.com,they@domain.com"}
{mailto address="me@domain.com" extra='class="email"'}

OUTPUT:

<a href="mailto:me@domain.com" >me@domain.com</a>
<a href="mailto:me@domain.com" >send me some mail</a>
<SCRIPT language="javascript">eval(unescape('%64%6f%63%75%6d%65%6e%74%2e%77%72%6
9%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%
61%69%6e%2e%63%6f%6d%22%20%3e%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%3c%2f%61%3e
%27%29%3b'))</SCRIPT>
<a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d" >&#x6d;&#x65;&#x40;&#x64;&
#x6f;&#x6d;&#x61;&#x69;&#x6e;&#x2e;&#x63;&#x6f;&#x6d;</a>
<a href="mailto:me@domain.com?subject=Hello%20to%20you%21" >me@domain.com</a>
<a href="mailto:me@domain.com?cc=you@domain.com%2Cthey@domain.com" >me@domain.com</a>
<a href="mailto:me@domain.com" class="email">me@domain.com</a>

Prev | Home | Next
math | Up | popup_init


popup_init

popup is an integration of overLib, a library used for popup windows. These are used for context sensitive information, such as help windows or tooltips. popup_init must be called once at the top of any page you plan on using the popup function. overLib was written by Erik Bosrup, and the homepage is located at http://www.bosrup.com/web/overlib/.

popup 函数整合了 overLib(用于弹出窗口的函数库) 库. 这些函数用于上下文敏感信息如帮助窗口或工具提示. 如果准备使用 popup 函数，在页首必须先调用 popup_init 函数. overLib 由 Erik Bosrup 开发，其主页位于http://www.bosrup.com/web/overlib/.

As of Smarty version 2.1.2, overLib does NOT come with the release. Download overLib, place the overlib.js file under your document root and supply the relative path to this file as the "src" parameter to popup_init.

在 Smarty 2.1.2 版中没有带 overLib 库. 必须下载该库，将 overlib.js 文件置于文档根目录下，调用 popup_init 的时候将该文件的相对路径作为参数"src"传递.

Example 8-16. popup_init
例 8-16. popup_init 函数演示

{* popup_init must be called once at the top of the page *}
{popup_init src="/javascripts/overlib.js"}

Prev | Home | Next
mailto | Up | popup


popup

Attribute Name | Type | Required | Default | Description
text | string | Yes | n/a | the text/html to display in the popup window
trigger | string | No | onMouseOver | What is used to trigger the popup window. Can be one of onMouseOver or onClick
sticky | boolean | No | false | Makes the popup stick around until closed
caption | string | No | n/a | sets the caption to title
fgcolor | string | No | n/a | color of the inside of the popup box
bgcolor | string | No | n/a | color of the border of the popup box
textcolor | string | No | n/a | sets the color of the text inside the box
capcolor | string | No | n/a | sets color of the box's caption
closecolor | string | No | n/a | sets the color of the close text
textfont | string | No | n/a | sets the font to be used by the main text
captionfont | string | No | n/a | sets the font of the caption
closefont | string | No | n/a | sets the font for the "Close" text
textsize | string | No | n/a | sets the size of the main text's font
captionsize | string | No | n/a | sets the size of the caption's font
closesize | string | No | n/a | sets the size of the "Close" text's font
width | integer | No | n/a | sets the width of the box
height | integer | No | n/a | sets the height of the box
left | boolean | No | false | makes the popups go to the left of the mouse
right | boolean | No | false | makes the popups go to the right of the mouse
center | boolean | No | false | makes the popups go to the center of the mouse
above | boolean | No | false | makes the popups go above the mouse. NOTE: only possible when height has been set
below | boolean | No | false | makes the popups go below the mouse
border | integer | No | n/a | makes the border of the popups thicker or thinner
offsetx | integer | No | n/a | how far away from the pointer the popup will show up, horizontally
offsety | integer | No | n/a | how far away from the pointer the popup will show up, vertically
fgbackground | url to image | No | n/a | defines a picture to use instead of color for the inside of the popup.
bgbackground | url to image | No | n/a | defines a picture to use instead of color for the border of the popup. NOTE: You will want to set bgcolor to "" or the color will show as well. NOTE: When having a Close link, Netscape will re-render the table cells, making things look incorrect
closetext | string | No | n/a | sets the "Close" text to something else
noclose | boolean | No | n/a | does not display the "Close" text on stickies with a caption
status | string | No | n/a | sets the text in the browsers status bar
autostatus | boolean | No | n/a | sets the status bar's text to the popup's text. NOTE: overrides status setting
autostatuscap | string | No | n/a | sets the status bar's text to the caption's text. NOTE: overrides status and autostatus settings
inarray | integer | No | n/a | tells overLib to read text from this index in the ol_text array, located in overlib.js. This parameter can be used instead of text
caparray | integer | No | n/a | tells overLib to read the caption from this index in the ol_caps array
capicon | url | No | n/a | displays the image given before the popup caption
snapx | integer | No | n/a | snaps the popup to an even position in a horizontal grid
snapy | integer | No | n/a | snaps the popup to an even position in a vertical grid
fixx | integer | No | n/a | locks the popups horizontal position Note: overrides all other horizontal placement
fixy | integer | No | n/a | locks the popups vertical position Note: overrides all other vertical placement
background | url | No | n/a | sets image to be used instead of table box background
padx | integer,integer | No | n/a | pads the background image with horizontal whitespace for text placement. Note: this is a two parameter command
pady | integer,integer | No | n/a | pads the background image with vertical whitespace for text placement. Note: this is a two parameter command
fullhtml | boolean | No | n/a | allows you to control the html over a background picture completely. The html code is expected in the "text" attribute
frame | string | No | n/a | controls popups in a different frame. See the overlib page for more info on this function
timeout | string | No | n/a | calls the specified javascript function and takes the return value as the text that should be displayed in the popup window
delay | integer | No | n/a | makes that popup behave like a tooltip. It will popup only after this delay in milliseconds
hauto | boolean | No | n/a | automatically determine if the popup should be to the left or right of the mouse.
vauto | boolean | No | n/a | automatically determine if the popup should be above or below the mouse.

属性 | 类型 | 是否必须 | 缺省值 | 描述
text | string | Yes | n/a | 弹出窗口中要显示的内容，文本或超文本
trigger | string | No | onMouseOver | 触发弹出窗口的条件，可选择onMouseOver(鼠标经过)或onClick(鼠标单击)
sticky | boolean | No | false | 弹出窗口始终显示，直到关闭
caption | string | No | n/a | 标题文本内容
fgcolor | string | No | n/a | 弹出窗口内部颜色
bgcolor | string | No | n/a | 弹出窗口边框颜色
textcolor | string | No | n/a | 弹出窗口内部文字颜色
capcolor | string | No | n/a | 弹出窗口标题颜色
closecolor | string | No | n/a | 设置"关闭"文本信息的颜色
textfont | string | No | n/a | 设置内容文本使用的字体类型
captionfont | string | No | n/a | 设置标题文本的字体
closefont | string | No | n/a | 设置"关闭"文本信息的字体类型
textsize | string | No | n/a | 设置内容文本使用的字体大小
captionsize | string | No | n/a | 设置标题文本使用的字体大小
closesize | string | No | n/a | 设置"关闭"文本信息的字体大小
width | integer | No | n/a | sets the width of the box设置宽度
height | integer | No | n/a | sets the height of the box设置高度
left | boolean | No | false | 使弹出窗口位于鼠标左侧
right | boolean | No | false | 使弹出窗口位于鼠标右侧
center | boolean | No | false | 使弹出窗口的中间位置和鼠标位置重合
above | boolean | No | false | 使弹出窗口位于鼠标上侧. 注: 仅在设置了height属性时有效
below | boolean | No | false | 使弹出窗口位于鼠标下侧
border | integer | No | n/a | 决定弹出窗口的边框厚度
offsetx | integer | No | n/a | 横向显示位置偏移量
offsety | integer | No | n/a | 纵向显示位置偏移量
fgbackground | url to image | No | n/a | 使用背景图片代替背景颜色
bgbackground | url to image | No | n/a | 使用背景图片代替边框颜色. 注1: 必须设置bgcolor为""，边框颜色才不会显示. 注2: 当有关闭链接时，Netscape会重新渲染表格，看起来可能会有点问题.
closetext | string | No | n/a | 自定义关闭链接显示文本
noclose | boolean | No | n/a | 不显示关闭链接
status | string | No | n/a | 设置状态栏显示的文本
autostatus | boolean | No | n/a | 设置弹出窗口状态栏显示的文本为当前窗口状态栏显示的文本. 注: 该设置将覆盖status的设置
autostatuscap | string | No | n/a | 设置状态栏显示的文本为标题栏显示的信息. 注: 该设置将覆盖status和autostatus设置
inarray | integer | No | n/a | 该属性告诉overLib在ol_text数组中读该属性指定的索引的元素到text中. 该属性可以代替text属性
caparray | integer | No | n/a | 该属性告诉overLib在ol_caps数组中读该属性指定的索引的元素到caption中.
capicon | url | No | n/a | 弹出前先显示该图象
snapx | integer | No | n/a | 横向将弹出窗口附着于指定位置
snapy | integer | No | n/a | 纵向将弹出窗口附着于指定位置
fixx | integer | No | n/a | 锁定弹出窗口的横向位置. 注: 该设置将覆盖其它横向设置
fixy | integer | No | n/a | 锁定弹出窗口的纵向位置. 注: 该设置将覆盖其它纵向设置
background | url | No | n/a | 设置图象作为输出表格区块的背景
padx | integer,integer | No | n/a | 在背景图象后附加横向空白. 注: 该属性有两个参数
pady | integer,integer | No | n/a | 在背景图象后附加纵向空白. 注: 该属性有两个参数
fullhtml | boolean | No | n/a | 允许用户完全控制背景图片上的HTML. HTML代码位于"text"属性中
frame | string | No | n/a | 控制弹出窗口在不同的框架中. 关于此函数更多详细信息，请查阅overlib文档.
timeout | string | No | n/a | 调用特定javascript脚本函数，将返回值显示在弹出窗口中.
delay | integer | No | n/a | 使得弹出窗口像一个工具提示，窗口将显示到该属性指定的时间(毫秒)
hauto | boolean | No | n/a | 自动决定弹出窗口位于鼠标的左侧或右侧.
vauto | boolean | No | n/a | 自动决定弹出窗口位于鼠标的上侧或下侧.

popup is used to create javascript popup windows.

popup 用于创建javascript弹出窗口.

Example 8-17. popup
例 8-17. popup 函数演示

{* popup_init must be called once at the top of the page *}
{popup_init src="/javascripts/overlib.js"}

{* create a link with a popup window when you move your mouse over *}
<A href="mypage.html" {popup text="This link takes you to my page!"}>mypage</A>

{* you can use html, links, etc in your popup text *}
<A href="mypage.html" {popup sticky=true caption="mypage contents"
text="<UL><LI>links<LI>pages<LI>images</UL>" snapx=10 snapy=10}>mypage</A>

Prev | Home | Next
popup_init | Up | textformat


textformat

Attribute Name | Type | Required | Default | Description
style | string | No | n/a | preset style
indent | number | No | 0 | The number of chars to indent every line
indent_first | number | No | 0 | The number of chars to indent the first line
indent_char | string | No | (single space) | The character (or string of chars) to indent with
wrap | number | No | 80 | How many characters to wrap each line to
wrap_char | string | No | \n | The character (or string of chars) to break each line with
wrap_cut | boolean | No | false | If true, wrap will break the line at the exact character instead of at a word boundary
assign | string | No | n/a | the template variable the output will be assigned to

属性 | 类型 | 是否必须 | 缺省值 | 描述
style | string | No | n/a | 预处理风格
indent | number | No | 0 | 单行缩进的字符数目
indent_first | number | No | 0 | 首行缩进的字符数目
indent_char | string | No | (single space) | 填充缩进区域的字符(或字符串)
wrap | number | No | 80 | 单行长度，超过该长度自动折行
wrap_char | string | No | \n | 折行使用的字符(或字符串)，被附加在行尾
wrap_cut | boolean | No | false | 如果设置为真，换行时不考虑换行点所在位置是否为完整单词，直接换行. 反之将在单词的边界处换行.
assign | string | No | n/a | 输出值将被赋给模板变量的名称

textformat is a block function used to format text. It basically cleans up spaces and special characters, and formats paragraphs by wrapping at a boundary and indenting lines.

textformat 用于格式化文本. 该函数主要清理空格和特殊字符，对段落按单词边界换行和行缩进等段落格式化处理.

You can set the parameters explicitly, or use a preset style. Currently "email" is the only available style.

用户可以明确设置各参数，或使用预处理风格. 目前只有唯一可用风格"email".

Example 8-18. textformat
例 8-18. textformat 函数演示

{textformat wrap=40}

This is foo.
This is foo.
This is foo.
This is foo.
This is foo.
This is foo.

This is bar.

bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.

{/textformat}

OUTPUT:

This is foo. This is foo. This is foo.
This is foo. This is foo. This is foo.

This is bar.

bar foo bar foo foo. bar foo bar foo
foo. bar foo bar foo foo. bar foo bar
foo foo. bar foo bar foo foo. bar foo
bar foo foo. bar foo bar foo foo.

{textformat wrap=40 indent=4}

This is foo.
This is foo.
This is foo.
This is foo.
This is foo.
This is foo.

This is bar.

bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.

{/textformat}

OUTPUT:

 This is foo. This is foo. This is
 foo. This is foo. This is foo. This
 is foo.

 This is bar.

 bar foo bar foo foo. bar foo bar foo
 foo. bar foo bar foo foo. bar foo
 bar foo foo. bar foo bar foo foo.
 bar foo bar foo foo. bar foo bar
 foo foo.

{textformat wrap=40 indent=4 indent_first=4}

This is foo.
This is foo.
This is foo.
This is foo.
This is foo.
This is foo.

This is bar.

bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.

{/textformat}

OUTPUT:

 This is foo. This is foo. This
 is foo. This is foo. This is foo.
 This is foo.

 This is bar.

 bar foo bar foo foo. bar foo bar
 foo foo. bar foo bar foo foo. bar
 foo bar foo foo. bar foo bar foo
 foo. bar foo bar foo foo. bar foo
 bar foo foo.

{textformat style="email"}

This is foo.
This is foo.
This is foo.
This is foo.
This is foo.
This is foo.

This is bar.

bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.
bar foo bar foo foo.

{/textformat}

OUTPUT:

This is foo. This is foo. This is foo. This is foo. This is foo. This is
foo.

This is bar.

bar foo bar foo foo. bar foo bar foo foo. bar foo bar foo foo. bar foo
bar foo foo. bar foo bar foo foo. bar foo bar foo foo. bar foo bar foo
foo.
Prev | Home | Next
popup | Up | Config Files


Config Files

Prev Next

Chapter 9. Config Files

第九章.配置文件

Config files are handy for designers to manage global template variables from one file. One example is template colors. Normally if you wanted to change the color scheme of an application, you would have to go through each and every template file and change the colors. With a config file, the colors can be kept in one place, and only one file needs to be updated.

配置文件有利于设计者管理文件中的模板全局变量。最简单的例子就是模板色彩变量。一般情况下你如果想改变一个程序的外观色彩，你就必须通过去更改每一个文件的颜色变量。如果有这个配置文件的话，色彩变量就可以保存在一个地方，只要改变这个配置文件就可以实现你色彩的更新。

Example 9-1. Example of config file syntax

例 9-1 配置文件语法例子

# 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

Values of config file variables can be in quotes, but not necessary. You can use either single or double quotes. If you have a value that spans more than one line, enclose the entire value with triple quotes ("""). You can put comments into config files by any syntax that is not a valid config file syntax. We recommend using a # (hash) at the beginning of the line.

配置文件变量值能够在引号中使用，但是没有必要。你可以用单引号或者双引号。如果你有一个不只在一个区域内使用的变量值，你可以使用三引号(""")将它完整的封状起来，可以把它们放金配置文件，只要没有语法错误。我们建议在程序行前使用 “#”加一些注释信息来标示。

This config file example has two sections. Section names are enclosed in brackets []. Section names can be arbitrary strings not containing [ or ] symbols. The four variables at the top are global variables, or variables not within a section. These variables are always loaded from the config file. If a particular section is loaded, then the global variables and the variables from that section are also loaded. If a variable exists both as a global and in a section, the section variable is used. If you name two variables the same within a section, the last one will be used.

上面关于配置文件的例子共有两个部分。每部分的名称都是用一个“[]”给括起来。每部分的名称命名规则就是任意的字符串，只要不包括有符号“[”或者“]”。例子开头的四个变量都是全局变量，也就是说不仅仅是可以在一个区域内使用。这些变量总是从配置文件中载入。如果某个特定的局部变量已经载入，这样全局变量和局部变量都还可以载入。如果当某个变量名既是全局变量又是局部变量时，局部变量将被优先赋予值来使用。如果在一个局部中两个变量名相同的话，最后一个将被赋值使用。

Config files are loaded into templates with the built-in function {config_load} .

配置文件是通过内建函数载入到模板 { config load }

You can hide variables or entire sections by prepending the variable name or section name with a period. This is useful if your application reads the config files and gets sensitive data from them that the template engine does not need. If you have third parties doing template editing, you can be certain that they cannot read sensitive data from the config file by loading it into the template.

你可以在某个段时期通过预先想好的变量名或者局部名隐藏变量或者完整的一个节。当你的应用程序读取配置文件和取得有用数据而不用读取模板时这个非常有用，如果你有第三方来做模板编辑的话，可以肯定的说它们不能通过载入配置文件到模板而读取到任何有用的数据。

Prev | Home | Next
textformat | Up | Debugging Console


Debugging Console

Prev Next

Chapter 10. Debugging Console

第十章.调试控制台

There is a debugging console included with Smarty. The console informs you of all the included templates, assigned variables and config file variables for the current invocation of the template. A template named "debug.tpl" is included with the distribution of Smarty which controls the formatting of the console. Set $debugging to true in Smarty, and if needed set $debug_tpl to the template resource path for debug.tpl (this is in SMARTY_DIR by default.) When you load the page, a javascript console window should pop up and give you the names of all the included templates and assigned variables for the current page. To see the available variables for a particular templates, see the {debug} template function. To disable the debugging console, set $debugging to false. You can also temporarily turn on the debugging console by putting SMARTY_DEBUG in the URL if you enable this option with $debugging_ctrl.

SMARTY里面包括有一个调式控制台。它可以告诉你模板里面包含的所有内容，同时也可以为当前使用模板中的变量和配置文件变量赋值。一个叫 debug.tpl 的模板包含了很多控制调式控制台格式化的SMARTY类，在SMARTY中把变量 $debugging 设置为 true ，如果需要的话设置变量 $debug_tpl 为模板源文件路径（在SMARTY_DIR用已经自定义）。当你载入页面时，有一个JAVASCRIPT控制台窗口将弹出且告诉你所有模板中包含的名称和当前页已经赋值的变量。如果要了解某个模板的详细变量，可以去看 {debug} 模板定义函数章节。如果要关闭掉调试控制台，设置变量 $debugging 为 false 就可以了。如果你开启了 $debugging ctrl 选项，也可以通过放置 SMARTY_DEBUG 在 URL 来临时打开调试控制台。

Technical Note: The debugging console does not work when you use the fetch() API, only when using display(). It is a set of javascript statements added to the very bottom of the generated template. If you do not like javascript, you can edit the debug.tpl template to format the output however you like. Debug data is not cached and debug.tpl info is not included in the output of the debug console.

技术提示：当你使用函数 fetch() API 时调试控制台不能用，在使用 display() 时才可以使用。它将自动地把 javascript 添加到已经应用模板的每一个按扭中。如果你不喜欢 javascript ，你可以编辑文件 debug.tpl 模板，格式化输出为你自己喜欢的格式。调试数据是没有被缓存的，并且 debug.tpl 信息也没有包含在调试控制台的输出文件中。

Note: The load times of each template and config file are in seconds, or fractions thereof.

注意：每个模板和配置文件的载入都是以秒来计算的，甚至是以几分之一秒。

Prev | Home | Next
Config Files | Up | Smarty For Programmers


Smarty For Programmers

Prev Next

III. Smarty For Programmers
程序员篇

Table of Contents [内容列表]
11. Constants
[常量]
12. Variables
[变量]
13. Methods
[方法]
14. Caching
[缓存]
15. Advanced Features
[高级属性]
16. Extending Smarty With Plugins [利用插件扩展Smarty]
Prev | Home | Next
Debugging Console 调试控制器 |  | Constants 常量


Constants

Prev Next

Chapter 11. Constants
第十一章 常量

Table of Contents
内容列表
SMARTY_DIR [Smarty目录]

SMARTY_DIR
Smarty目录

This should be the full system path to the location of the Smarty class files. If this is not defined, then Smarty will attempt to determine the appropriate value automatically. If defined, the path must end with a slash.
定位Smarty类文件的完整系统路径，如果没有定义Smarty目录，Smarty将会试着自动创建合适的值。如果定义了,路径必须要以斜线结束。

Example 11-1. SMARTY_DIR

// set path to Smarty directory
define("SMARTY_DIR","/usr/local/lib/php/Smarty/");

require_once(SMARTY_DIR."Smarty.class.php");

Prev | Home | Next
Smarty For Programmers 程序员篇 | Up | Variables 变量


Variables

Prev Next

Chapter 12. Variables
第十二章 变量

Table of Contents [内容列表]
$template_dir [模板目录变量]
$compile_dir [编译目录变量]
$config_dir [配置目录变量]
$plugins_dir [插件目录变量]
$debugging [调试变量]
$debug_tpl调试模板变量
$debugging_ctrl [调试控制变量]
$global_assign [全局配置变量]
$undefined [未定义变量]
$autoload_filters [自动加载过滤器变量]
$compile_check [编译检查变量]
$force_compile [强迫编译变量]
$caching [缓存变量]
$cache_dir [缓存目录变量]
$cache_lifetime [缓存生存时间变量]
$cache_handler_func [缓存处理函数变量]
$cache_modified_check [缓存修正检查变量]
$config_overwrite [配置覆盖变量]
$config_booleanize [配置布尔化变量]
$config_read_hidden [配置读取隐藏变量]
$config_fix_newlines [配置固定换行符变量]
$default_template_handle r_func [默认模板处理函数变量]
$php_handling [PHP处理变量]
$security [安全变量]
$secure_dir [安全目录变量]
$security_settings [安全配置变量]
$trusted_dir [信任目录变量]
$left_delimiter [左结束符变量]
$right_delimiter [右结束符变量]
$compiler_class [编译类变量]
$request_vars_order [变量顺序变量]
$request_use_auto_globals [自动全局变量]
$compile_id [编译ID变量]
$use_sub_dirs [子目录变量]
$default_modifiers [默认修正器变量]
$default_resource_type [默认源类型变量]

$template_dir
模板目录变量

This is the name of the default template directory. If you do not supply a resource type when including files, they will be found here. By default this is "./templates", meaning that it will look for the templates directory in the same directory as the executing php script.
该变量定义默认模板目录的名字。当包含文件时，如果不提供一个源类型（即源地址），那么将会到模板目录中寻找。默认情况下，目录是：“./templates”，也就是说他将会在和php执行脚本相同的目录下寻找模板目录。

Technical Note: It is not recommended to put this directory under the web server document root.
技巧注意：不推荐把模板目录放在web服务器根目录下。

Prev | Home | Next
Constants[常量] | Up | [编译目录变量]$compile_dir


$compile_dir

Prev Chapter 12. Variables
第十二章 变量 		Next

$compile_dir
编译目录变量

This is the name of the directory where compiled templates are located. By default this is "./templates_c", meaning that it will look for the compile directory in the same directory as the executing php script.
该变量定位编译模板的目录名字。默认情况下，目录是：“./templates_c”，也就是说他将会在和php执行脚本相同的目录下寻找编译目录。

Technical Note: This setting must be either a relative or absolute path. include_path is not used for writing files.
技巧：该设置必须是一个相对或绝对路径。包含路径不用于写文件。

Technical Note: It is not recommended to put this directory under the web server document root.
技巧：不推荐把编译目录放在web服务器根目录下。

Prev | Home | Next
Variables[变量] | Up | [配置目录变量]$config_dir


$config_dir

Prev Chapter 12. Variables
第十二章 变量 		Next

$config_dir
配置目录变量

This is the directory used to store config files used in the templates. Default is "./configs", meaning that it will look for the configs directory in the same directory as the executing php script.
该变量定义用于存放模板配置文件的目录，默认情况下，目录是：“./configs”，也就是说他将会在和php执行脚本相同的目录下寻找配置目录。

Technical Note: It is not recommended to put this directory under the web server document root.
技巧：不推荐把编译目录放在web服务器根目录下。

Prev | Home | Next
$compile_dir[编译目录变量] | Up | [插件目录变量]$plugins_dir


$plugins_dir

Prev Chapter 12. Variables
第十二章 变量 		Next

$plugins_dir
插件目录变量

This is the directories where Smarty will look for the plugins that it needs. Default is "plugins" under the SMARTY_DIR. If you supply a relative path, Smarty will first look under the SMARTY_DIR, then relative to the cwd (current working directory), then relative to each entry in your PHP include path.
该变量定义Smarty寻找所需插件的目录。默认是在SMARTY目录下的“plugins”目录。如果提供了一个相对路径，Smarty将首先在SMARTY目录下寻找，然后到当前工作目录下寻找，继而到php包含路径中的每个路径中寻找。

Technical Note: For best performance, do not setup your plugins_dir to have to use the PHP include path. Use an absolute pathname, or a path relative to SMARTY_DIR or the cwd.
技巧：为了获取最好性能，不要将插件目录安装成必须使用php包含路径的境地。最好用一个绝对路径名字，或者是一个相对SMARTY目录或当前工作目录的路径。

Prev | Home | Next
$config_dir[配置目录变量] | Up | [调试变量]$debugging


$debugging

Prev Chapter 12. Variables
第十二章 变量 		Next

$debugging
调试变量

This enables the debugging console. The console is a javascript window that informs you of the included templates and assigned variables for the current template page.
它能启动调试控制台。该控制台是一个javascript窗口，该窗口告诉你被包含的模板和应用于当前模板页面的变量。

Prev | Home | Next
$plugins_dir[插件目录变量] | Up | [调试模板变量]$debug_tpl


$debug_tpl

Prev Chapter 12. Variables
第十二章 变量 		Next

$debug_tpl
调试模板

This is the name of the template file used for the debugging console. By default, it is named debug.tpl and is located in the SMARTY_DIR.
该变量定义用于调试控制台的模板文件名字。默认情况下，其名字为：debug.tpl，位于Smarty目录中。

Prev | Home | Next
$debugging[调试变量] | Up | [调试控制变量]$debugging_ctrl


$debugging_ctrl

Prev Chapter 12. Variables
第十二章 变量 		Next

$debugging_ctrl
调试控制变量

This allows alternate ways to enable debugging. NONE means no alternate methods are allowed. URL means when the keyword SMARTY_DEBUG is found in the QUERY_STRING, debugging is enabled for that invocation of the script. If $debugging is true, this value is ignored.
该变量作用是允许以交替的方式启动调试设置。NONE表示不允许交替方式。URL表示当关键词SMARTY_DEBUG出现在QUERY_STRING（查询字符串）中时，针对此脚本的调用，调试被启动。如果$debugging变量是真，则忽略其调试控制变量值。

Prev | Home | Next
$debug_tpl[调试模板变量] | Up | [全局配置变量]$global_assign


$global_assign

Prev Chapter 12. Variables
第十二章 变量 		Next

$global_assign
全局配置变量

This is a list of variables that are always implicitly assigned to the template engine. This is handy for making global variables or server variables available to all templates without having to manually assign them. Each element in the $global_assign should be either a name of the global variable, or a key/value pair, where the key is the name of the global array and the value is the array of variables to be assigned from that global array. $SCRIPT_NAME is globally assigned by default from $HTTP_SERVER_VARS.
定义一组总是隐式地作用于模板引擎的变量列表。这对于使全局变量或服务器变量可用于所有模板是很方便的，因为无需手工配置它们。在全局配置中的每一元素应当要么是一全局变量的名字，要么是一键/值对（键是全局数组名，值是对应该全局数组的变量数组）。$SCRIPT_NAME变量默认属于$HTTP_SERVER_VARS数组。

Technical Note: Server variables can be accessed through the $smarty variable, such as {$smarty.server.SCRIPT_NAME}. See the section on the $smarty variable.
技巧：服务器变量可以通过$smarty变量获得，如{$smarty.server.SCRIPT_NAME}。参看$smarty变量一节。

Prev | Home | Next
$debugging_ctrl[调试控制变量] | Up | [未定义变量]$undefined


$undefined

Prev Chapter 12. Variables
第十二章 变量 		Next

$undefined
未定义变量

This sets the value of $undefined for Smarty, default is null. Currently this is only used to set undefined variables in $global_assign to a default value.
该变量为Smarty设定没有得到定义的变量的值,默认为空.当前仅用来设定全局配置中的未定义变量为一个默认值.

Prev | Home | Next
$global_assign[全局配置变量] | Up | [自动加载过滤器变量]$autoload_filters


$autoload_filters

Prev Chapter 12. Variables
第十二章 变量 		Next

$autoload_filters
自动加载过滤器变量

If there are some filters that you wish to load on every template invocation, you can specify them using this variable and Smarty will automatically load them for you. The variable is an associative array where keys are filter types and values are arrays of the filter names. For example:
如果你希望在每次模板调用过程中加载过滤器,你可以指定他们使用此变量,Smarty将自动为你加载它们.该变量是一个联合数组,在数组中键是过滤器类型,值是过滤器名字所组成的数组.例如:

$smarty->autoload_filters = array('pre' => array('trim', 'stamp'),
 'output' => array('convert'));

Prev | Home | Next
$undefined[未定义变量] | Up | [编译检查变量]$compile_check


$compile_check

Prev Chapter 12. Variables
第十二章 变量 		Next

$compile_check
编译检查变量

Upon each invocation of the PHP application, Smarty tests to see if the current template has changed (different time stamp) since the last time it was compiled. If it has changed, it recompiles that template. If the template has not been compiled, it will compile regardless of this setting. By default this variable is set to true. Once an application is put into production (templates won't be changing), the compile_check step is no longer needed. Be sure to set $compile_check to "false" for maximal performance. Note that if you change this to "false" and a template file is changed, you will *not* see the change since the template will not get recompiled. If caching is enabled and compile_check is enabled, then the cache files will get regenerated if an involved template file or config file was updated. See $force_compile or clear_compiled_tpl.
每次调用PHP应用程序,Smarty 会试着查看自上次编译时间以来,当前模板是否被修改过.如果修改过了,她会重新编译那个模板.如果模板还没有被编译过,她将编译模板而不管编译检查如何设置.默认情况下编译检查这个变量设置为true.一旦一个应用程序投入产品中(模板将不会修改了),就不再需要编译检查这一步了.为了最大性能,确定将$compile_check设为"false".注意:如果设为了"false",虽然模板文件被修改,但你不会看到修改结果,因为模板没有得到重新编译.如果启动了缓存和编译检查,一旦有关模板文件或配置文件被更新,缓存文件将会重建.

Prev | Home | Next
$autoload_filters[自动加载过滤器变量] | Up | [强迫编译变量]$force_compile


$force_compile

Prev Chapter 12. Variables
第十二章 变量 		Next

$force_compile
强迫编译变量

This forces Smarty to (re)compile templates on every invocation. This setting overrides $compile_check. By default this is disabled. This is handy for development and debugging. It should never be used in a production environment. If caching is enabled, the cache file(s) will be regenerated every time.
强迫Smarty每次调用(重新)编译模板时.这项设置不受$compile_check的限制.默认情况下,它是无效的.它对于开发和调试很方便.但它决不能使用于产品环境下.如果启动了缓存,每次将会重新生成缓存文件.

Prev | Home | Next
$compile_check[编译检查变量] | Up | [缓存变量]$caching


$caching

Prev Chapter 12. Variables
第十二章 变量 		Next

$caching
缓存变量

This tells Smarty whether or not to cache the output of the templates. By default this is set to 0, or disabled. If your templates generate redundant redundant content, it is advisable to turn on caching. This will result in significant performance gains. You can also have multiple caches for the same template. A value of 1 or 2 enables caching. 1 tells Smarty to use the current $cache_lifetime variable to determine if the cache has expired. A value of 2 tells Smarty to use the cache_lifetime value at the time the cache was generated. This way you can set the cache_lifetime just before fetching the template to have granular control over when that particular cache expires. See also is_cached.
告诉Smarty是否缓存模板的输出.默认情况下,她设为0,或无效.如果模板产生冗余内容,建议打开缓存.这样有利于获得良好的性能增益.你也可以为同一模板设有多个缓存.当值为1或2时启动缓存.1告诉Smarty 使用当前的$cache_lifetime变量判断缓存是否过期.2告诉 Smarty 使用生成缓存时的cache_lifetime值.用这种方式你正好可以在获取模板之前设置缓存生存时间，以便较精确地控制缓存何时失效.

If $compile_check is enabled, the cached content will be regenerated if any of the templates or config files that are part of this cache are changed. If $force_compile is enabled, the cached content will always be regenerated.
如果启动了编译检查,一旦任何的模板文件或配置文件(有关缓存部分的配置文件)被修改,缓存的内容将会重新生成.如果启动了强迫编译,缓存的内容将总会重新生成.

Prev | Home | Next
$force_compile[强迫编译变量] | Up | [编译目录变量]$cache_dir


$cache_dir

Prev Chapter 12. Variables
第十二章 变量 		Next

$cache_dir
缓存目录变量

This is the name of the directory where template caches are stored. By default this is "./cache", meaning that it will look for the cache directory in the same directory as the executing php script. You can also use your own custom cache handler function to control cache files, which will ignore this setting.
这是存放模板缓存的目录名.默认情况下,它是:"./cache",也就是说你可以在和php执行脚本相同目录下寻找缓存目录.你也可以用你自己的自定义缓存处理函数来控制缓存文件,它将会忽略这项设置.

Technical Note: This setting must be either a relative or absolute path. include_path is not used for writing files.
技巧:这项设置必须是一个相对或绝对路径.包含路径不用于写文件.

Technical Note: It is not recommended to put this directory under the web server document root.
技巧:不推荐将此目录放在web服务器根目录下.

Prev | Home | Next
$caching[缓存变量] | Up | [缓存生存时间变量]$cache_lifetime


$cache_lifetime

Prev Chapter 12. Variables
第十二章 变量 		Next

$cache_lifetime
缓存生存时间变量

This is the length of time in seconds that a template cache is valid. Once this time has expired, the cache will be regenerated. $caching must be set to "true" for $cache_lifetime to have any purpose. A value of -1 will force the cache to never expire. A value of 0 will cause the cache to always regenerate (good for testing only, to disable caching a more efficient method is to set $caching = false.)
该变量定义模板缓存有效时间段的长度(单位秒),一旦这个时间失效,则缓存将会重新生成.如果要想实现所有效果,$caching必须因$cache_lifetime需要而设为"true".值为-1时,将强迫缓存永不过期.0值将导致缓存总是重新生成(仅有利于测试,一个更有效的使缓存无效的方法是设置$caching = false.)

If $force_compile is enabled, the cache files will be regenerated every time, effectively disabling caching. You can clear all the cache files with the clear_all_cache() function, or individual cache files (or groups) with the clear_cache() function.
如果启动了强迫编译,则缓存文件每次将会重新生成.要想有效地停止缓存,你可以利用clear_all_cache() 函数清除所有的缓存文件,或者利用clear_cache() 函数清除个别文件(或文件组).

Technical Note: If you want to give certain templates their own cache lifetime, you could do this by setting $caching = 2, then set $cache_lifetime to a unique value just before calling display() or fetch().
技巧:如果你想给某些模板设定它们自己的缓存生存时间,你可以在调用display()或fetch()函数之前,通过设置$caching = 2,然后设置$cache_lifetime为一个唯一值来实现.

Prev | Home | Next
$cache_dir[缓存目录变量] | Up | [缓存处理函数变量]$cache_handler_func


$cache_handler_func

Prev Chapter 12. Variables
第十二章 变量 		Next

$cache_handler_func
缓存处理函数变量

You can supply a custom function to handle cache files instead of using the built-in method using the $cache_dir. See the custom cache handler function section for details.
你可以提供一个自定义函数来处理缓存文件,而不是通过变量$cache_dir使用内置方法.祥见:cache handler function section

Prev | Home | Next
$cache_lifetime[缓存生存时间变量] | Up | [缓存编译检查变量]$cache_modified_check


$cache_modified_check

Prev Chapter 12. Variables
第十二章 变量 		Next

$cache_modified_check
缓存修改检查变量

If set to true, Smarty will respect the If-Modified-Since header sent from the client. If the cached file timestamp has not changed since the last visit, then a "304 Not Modified" header will be sent instead of the content. This works only on cached content without {insert} tags.
如果设置该变量为真,Smarty将分析客户端发送来的If-Modified-Since头信息.如果缓存文件时间戳自上次访问以来没有改变,则发送一个"304 Not Modified"头,而不是缓存文件内容.这种方式仅工作于没有 {insert} 标记的缓存内容.

Prev | Home | Next
$cache_handler_func[缓存处理函数变量] | Up | [配置覆盖变量]$config_overwrite


$config_overwrite

Prev Chapter 12. Variables
第十二章 变量 		Next

$config_overwrite
配置覆盖变量

If set to true, variables read in from config files will overwrite each other. Otherwise, the variables will be pushed onto an array. This is helpful if you want to store arrays of data in config files, just list each element multiple times. true by default.
如果设该变量为真,则从配置文件中读取出来的变量将会互相覆盖.否则,变量将会放到一个数组中.如果你想把配置文件中的数据存储到数组里,这种方式是很有用的,仅仅列出每个元素多次就可以了.默认情况下,设为真.

Prev | Home | Next
$cache_modified_check[编译修改检查] | Up | [配置布尔化变量]$config_booleanize


$config_booleanize

Prev Chapter 12. Variables
第十二章 变量 		Next

$config_booleanize
配置布尔化变量

If set to true, config file values of on/true/yes and off/false/no get converted to boolean values automatically. This way you can use the values in the template like so: {if #foobar#} ... {/if}. If foobar was on, true or yes, the {if} statement will execute. true by default.
如果该变量设为真,配置文件中的on/true/yes 和 off/false/no值会自动转化为布尔值.这样的话,你就可以在模板中像{if #foobar#} ... {/if}这样使用这些值了.如果foobar为on, true 或 yes,那么 {if}语句就会执行了.默认情况下,该变量值为真.

Prev | Home | Next
$config_overwrite[配置覆盖变量] | Up | [配置读取隐藏变量]$config_read_hidden


$config_read_hidden

Prev Chapter 12. Variables
第十二章 变量 		Next

$config_read_hidden
配置读取隐藏变量

If set to true, hidden sections (section names beginning with a period) in config files can be read from templates. Typically you would leave this false, that way you can store sensitive data in the config files such as database parameters and not worry about the template loading them. false by default.
如果设为真,在配置文件中的隐藏节块(******不会翻译啦)可以从模版中读取出来.典型的你会设为假,这样你可以在配置文件里存放敏感数据,例如数据库参数,而不用担心模版会调用他们.默认情况下,该变量设为假.

Prev | Home | Next
$config_booleanize[配置布尔化变量] | Up | [配置固定换行符变量]$config_fix_newlines


$config_fix_newlines

Prev Chapter 12. Variables
第十二章 变量 		Next

$config_fix_newlines
配置固定换行符变量

If set to true, mac and dos newlines (\r and \r\n) in config files are converted to \n when they are parsed. true by default.
如果该变量设为真,那么在配置文件中的mac 和 dos 换行符(\r and \r\n)在语法解析时将会转换为\n. 默认情况下,该变量为真.

Prev | Home | Next
$config_read_hidden[配置读取隐藏变量] | Up | [默认模板处理函数变量]$default_template_handler_func


$default_template_handler_func

Prev Chapter 12. Variables
第十二章 变量 		Next

$default_template_handler_func
默认模板处理函数变量

This function is called when a template cannot be obtained from its resource.
该函数在模板不能从它的源目录下获取时会得到调用.

Prev | Home | Next
$config_fix_newlines[配置固定换行符变量] | Up | [php处理变量]$php_handling


$php_handling

Prev Chapter 12. Variables
第十二章 变量 		Next

$php_handling
php处理变量

This tells Smarty how to handle PHP code embedded in the templates. There are four possible settings, default being SMARTY_PHP_PASSTHRU. Note that this does NOT affect php code within {php}{/php} tags in the template.
该变量告诉Smarty怎样处理嵌入到模版中的php代码.有四种可能的设置,默认为SMARTY_PHP_PASSTHRU.注意：改变量的设置不会影响模板里面{php}{/php}标记中的php代码.

  • SMARTY_PHP_PASSTHRU - Smarty echos tags as-is.Smarty
    原样输出标记.

  • SMARTY_PHP_QUOTE - Smarty quotes the tags as html entities.Smarty
    作为html实体引用标记

  • SMARTY_PHP_REMOVE - Smarty removes the tags from the templates.Smarty
    从模板中移出标记.

  • SMARTY_PHP_ALLOW - Smarty will execute the tags as PHP code.Smarty
    将作为php代码执行标记.

NOTE: Embedding PHP code into templates is highly discouraged. Use custom functions or modifiers instead.
极度不赞成将php代码嵌入到模板中.

Prev | Home | Next
$default_template_handler_func[默认模板处理函数变量] | Up | [安全变量]$security


$security

Prev Chapter 12. Variables
第十二章 变量 		Next

$security
安全变量

$security true/false, default is false. Security is good for situations when you have untrusted parties editing the templates (via ftp for example) and you want to reduce the risk of system security compromises through the template language. Turning on security enforces the following rules to the template language, unless specifially overridden with $security_settings:
安全变量要么是真,要么是假.默认为假.当你不信任模板中的可编辑部分(例如通过ftp方式上传编辑的),并想通过模板语言减小系统非安全的风险时,安全变量设为真比较适合.设为真会将下面的规则强加于模板语言中,除非特别地用$security_settings覆盖.

  • If $php_handling is set to SMARTY_PHP_ALLOW, this is implicitly changed to SMARTY_PHP_PASSTHRU
    如果变量$php_handling设为了SMARTY_PHP_ALLOW,则会隐式地被修改成SMARTY_PHP_PASSTHRU

  • PHP functions are not allowed in IF statements, except those specified in the $security_settings
    PHP函数在IF语句中是不允许的,除了在$security_settings中另行指出.

  • templates can only be included from directories listed in the $secure_dir array
    模板仅可以包含于$secure_dir数组列出的目录中.

  • local files can only be fetched from directories listed in the $secure_dir array using {fetch}
    本地文件仅可以用{fetch}获取于$secure_dir数组列出的目录中.

  • {php}{/php} tags are not allowed
    不允许有{php}{/php}标记.

  • PHP functions are not allowed as modifiers, except those specified in the $security_settings
    PHP函数不允许作为修正器,除了在$security_settings中指出.

Prev | Home | Next
$php_handling[php处理变量] | Up | [安全目录变量]$secure_dir


$secure_dir

Prev Chapter 12. Variables
第十二章 变量 		Next

$secure_dir
安全目录变量

This is an array of all local directories that are considered secure. {include} and {fetch} use this when security is enabled.
这是一个与安全有关的本地目录数组变量.当启动安全变量时{include} 和 {fetch}会用到此数组变量.

Prev | Home | Next
$security[安全变量] | Up | [安全配置变量]$security_settings


$security_settings

Prev Chapter 12. Variables
第十二章 变量 		Next

$security_settings
安全配置变量

These are used to override or specify the security settings when security is enabled. These are the possible settings:
用于当启动安全变量时覆盖或另行指定安全配置.有以下几种可能的配置:

  • PHP_HANDLING - true/false. If set to true, the $php_handling setting is not checked for security.
    PHP_HANDLING - 真或假.如果真,则不检查$php_handling的配置.

  • IF_FUNCS - This is an array of the names of permitted PHP functions in IF statements.
    IF_FUNCS - 这是一个可允许包含在if语句中的php函数名数组.

  • INCLUDE_ANY - true/false. If set to true, any template can be included from the file system, regardless of the $secure_dir list.
    INCLUDE_ANY - 真或假.如果真,可以从文件系统中包含任何模板,而不管$secure_dir目录设置如何.

  • PHP_TAGS - true/false. If set to true, {php}{/php} tags are permitted in the templates.
    PHP_TAGS - 真或假.如果真,{php}{/php}允许在模板中存在.

  • MODIFIER_FUNCS - This is an array of the names of permitted PHP functions used as variable modifiers.
    MODIFIER_FUNCS - 这是一个可用作修正器的php函数名数组.

Prev | Home | Next
$secure_dir[安全目录变量] | Up | [信任目录变量]$trusted_dir


$trusted_dir

Prev Chapter 12. Variables
第十二章 变量 		Next

$trusted_dir
信任目录变量

$trusted_dir is only for use when $security is enabled. This is an array of all directories that are considered trusted. Trusted directories are where you keep php scripts that are executed directly from the templates with {include_php}.
信任目录变量仅用在$security启动之后.这是一个所有建立信任的目录数组变量.你可以将php脚本放到这些信任目录中,这些脚本会直接在模板里以{include_php}标记得到执行.

Prev | Home | Next
$security_settings[安全配置变量] | Up | [左结束符变量]$left_delimiter


$left_delimiter

Prev Chapter 12. Variables
第十二章 变量 		Next

$left_delimiter
左结束符变量

This is the left delimiter used by the template language. Default is "{".
用于模板语言中,默认是"{".

Prev | Home | Next
$trusted_dir[信任目录变量] | Up | [右结束符变量]$right_delimiter


$right_delimiter

Prev Chapter 12. Variables
第十二章 变量 		Next

$right_delimiter
右结束符变量

This is the right delimiter used by the template language. Default is "}".
用于模板语言中,默认是"}".

Prev | Home | Next
$left_delimiter[左结束符变量] | Up | [编译类变量]$compiler_class


$compiler_class

Prev Chapter 12. Variables
第十二章 变量 		Next

$compiler_class
编译类变量

Specifies the name of the compiler class that Smarty will use to compile the templates. The default is 'Smarty_Compiler'. For advanced users only.指定Smarty用来编译模板的编译类名.默认为:'Smarty_Compiler'.仅适合于高级用户.

Prev | Home | Next
$right_delimiter[右结束符变量] | Up | [变量顺序变量]$request_vars_order


$request_vars_order

Prev Chapter 12. Variables
第十二章 变量 		Next

$request_vars_order
变量顺序变量

The order in which request variables are registered, similar to variables_order in php.ini
请求变量的顺序在这里配置,类似于php.ini中的变量顺序.

Prev | Home | Next
$compiler_class[编译类变量] | Up | [自动全局变量]$request_use_auto_globals


$compile_id

Prev Chapter 12. Variables
第十二章 变量 		Next

$compile_id
编译id变量

Persistant compile identifier. As an alternative to passing the same compile_id to each and every function call, you can set this compile_id and it will be used implicitly thereafter.
永久的编译鉴别号.作为一个可选办法将相同的编译号传递给每个函数调用,你可以设置这个编译id,随后此id将会被隐含地使用.

Prev | Home | Next
$request_use_auto_globals[自动全局变量] | Up | [子目录变量]$use_sub_dirs


$use_sub_dirs

Prev Chapter 12. Variables
第十二章 变量 		Next

$use_sub_dirs
子目录变量

Set this to false if your PHP environment does not allow the creation of sub directories by Smarty. Sub directories are more efficient, so use them if you can.
如果你的php环境不允许Smarty创建子目录,则设此变量为假.子目录非常有用,所以尽可能的使用他们.

Prev | Home | Next
$compile_id[编译id变量] | Up | [默认修正器变量]$default_modifiers


$default_modifiers

Prev Chapter 12. Variables
第十二章 变量 		Next

$default_modifiers
默认修正器变量

This is an array of modifiers to implicitly apply to every variable in a template. For example, to HTML-escape every variable by default, use array('escape:"htmlall"'); To make a variable exempt from default modifiers, pass the special "smarty" modifier with a parameter value of "nodefaults" modifier to it, such as {$var|smarty:nodefaults}.
这是一个修正器数组变量,这些修正器隐式地作用于模板中的每个变量.例如:针对HTML,用数组('escape:"htmlall"')默认地忽略每个变量;为了使一个变量免除于默认修正器,请将参数为"nodefaults"的特殊"smarty"修正器作用于它,例如:{$var|smarty:nodefaults}.

Prev | Home | Next
$use_sub_dirs[子目录变量] | Up | [默认源类型变量]$default_resource_type


$default_resource_type

Prev Chapter 12. Variables
第十二章 变量 		Next

$default_resource_type
默认源类型变量

This tells smarty what resource type to use implicitly. The default value is 'file', meaning that $smarty->display('index.tpl'); and $smarty->display('file:index.tpl'); are identical in meaning. See the resource chapter for details.
该变量告诉smarty隐式地使用什么源类型.默认值为'file',也就是说,$smarty->display('index.tpl');和and $smarty->display('file:index.tpl');从意思上是一样的.祥见resource一章。

Prev | Home | Next
$default_modifiers[默认修正器变量] | Up | [方法]Methods


Methods

Prev
Next

Chapter 13. Methods 第13章. 方法

Table of Contents 目录
append 添加
append_by_ref 引用添加
assign 赋值
assign_by_ref 引用赋值
clear_all_assign 清除所有赋值
clear_all_cache 清除所有缓存
clear_assign 清除赋值
clear_cache 清除缓存
clear_compiled_tpl 清除已编译模板
clear_config 清除配置
config_load 加载配置
display 显示
fetch 取得输出的内容
get_config_vars 取配置变量的值
get_registered_object 取得已注册的对象
get_template_vars 取得模板变量的值
is_cached 是否已被缓存
load_filter 加载过滤器
register_block 注册一个块
register_compiler_function 注册编译函数
register_function 注册函数
register_modifier 注册修饰器
register_object 注册对象
register_outputfilter 注册输出过滤器
register_postfilter 注册提交过滤器
register_prefilter 注册预过滤器
register_resource 注册资源
trigger_error 触发错误
template_exists 模板是否存在
unregister_block 注销一个块
unregister_compiler_function 注销编译函数
unregister_function 注销函数
unregister_modifier 注销修饰器
unregister_object 注销对象
unregister_outputfilter 注销输出过滤器
unregister_postfilter 注销提交过滤器
unregister_prefilter 注销预过滤器
unregister_resource 注销资源

append 添加

void append (mixed var)

void append (string varname, mixed var)

void append (string varname, mixed var, boolean merge)

This is used to append an element to an assigned array. If you append to a string value, it is converted to an array value and then appended to. You can explicitly pass name/value pairs, or associative arrays containing the name/value pairs. If you pass the optional third parameter of true, the value will be merged with the current array instead of appended.

添加指定的元素到数组中。如果是添加一个字符串，该字符串会被转换为数组格式后再进行添加。所添加的数据可以采用 名称, 数值 的格式，或者是使用 “=>”连接的联合数组格式。如果第三个可选参数被指定为 TRUE，所添加的数据会和数组中现有数据进行合并，而不是直接添加。

Technical Note: The merge parameter respects array keys, so if you merge two numerically indexed arrays, they may overwrite each other or result in non-sequential keys. This is unlike the array_merge() function of PHP which wipes out numerical keys and renumbers them.

注意：使用第三个参数“merge”时要考虑到数组的索 引，所以，如果添加和被添加的数组都是以数字为索引，他们会互相覆盖，或者产生不连续的索引。这并不象PHP中的array_merge()函数，后者会 删除原有的数字索引，重新对索引进行编号。

Example 13-1. append 例子 13-1. 添加

// passing name/value pairs 以 名称，数值 的方式添加
$smarty->append("Name","Fred");
$smarty->append("Address",$address);

// passing an associative array 以联合数组的方式添加
$smarty->append(array("city" => "Lincoln","state" => "Nebraska"));

Prev | Home | Next
$default_resource_type 默认资源类型 | Up | append_by_ref 引用添加


append_by_ref

Prev Chapter 13. Methods Next

append_by_ref
引用添加

void append_by_ref (string varname, mixed var)

void append_by_ref (string varname, mixed var, boolean merge)

This is used to append values to the templates by reference. If you append a variable by reference then change its value, the appended value sees the change as well. For objects, append_by_ref() also avoids an in-memory copy of the appended object. See the PHP manual on variable referencing for an in-depth explanation. If you pass the optional third parameter of true, the value will be merged with the current array instead of appended.

本函数用于采用引用的方式把变量的值添加到原有值之后。如果采用引用的方式添加了一个变量，那么当这个变量的值改变时，被添加的值也随之改变。对于 对象，append_by_ref()函数也能够避免对于被添加对象的内存拷贝。关于变量引用的进一步解释可以查看PHP手册。如果第三个可选参数设置为 true，数值将会和现有数组合并，而不是添加在数组后面。

Technical Note: The merge parameter respects array keys, so if you merge two numerically indexed arrays, they may overwrite each other or result in non-sequential keys. This is unlike the array_merge() function of PHP which wipes out numerical keys and renumbers them.

注意：使用第三个参数“merge”时要考虑到数组的索 引，所以，如果添加和被添加的数组都是以数字为索引，他们会互相覆盖，或者产生不连续的索引。这并不象PHP中的array_merge()函数，后者会 删除原有的数字索引，重新对索引进行编号。

Example 13-2. append_by_ref
例子 13-2. 引用添加

// appending name/value pairs
$smarty->append_by_ref("Name",$myname);
$smarty->append_by_ref("Address",$address);

Prev | Home | Next
Methods 方法 | Up | assign 赋值


assign

Prev Chapter 13. Methods Next

assign
赋值

void assign (mixed var)

void assign (string varname, mixed var)

This is used to assign values to the templates. You can explicitly pass name/value pairs, or associative arrays containing the name/value pairs.

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

Example 13-3. assign
例子 13-3. 赋值

// passing name/value pairs 名称/数值 方式
$smarty->assign("Name","Fred");
$smarty->assign("Address",$address);

// passing an associative array 联合数组方式
$smarty->assign(array("city" => "Lincoln","state" => "Nebraska"));

Prev | Home | Next
append_by_ref 引用添加 | Up | assign_by_ref 引用赋值


assign_by_ref

Prev Chapter 13. Methods Next

assign_by_ref
引用赋值

void assign_by_ref (string varname, mixed var)

This is used to assign values to the templates by reference instead of making a copy. See the PHP manual on variable referencing for an explanation.

采用引用的方式赋值到模板中，而不是在模板中创建一个数值的副本。引用的概念可以查看PHP手册的变量引用部分。

Technical Note: This is used to assign values to the templates by reference. If you assign a variable by reference then change its value, the assigned value sees the change as well. For objects, assign_by_ref() also avoids an in-memory copy of the assigned object. See the PHP manual on variable referencing for an in-depth explanation.

注意：本函数用于采用引用的方式赋值到模板中。如果把一个 变量采用引用的方式赋值后，变量的值又被改变了，那么在模板中将会看到变量改变后的值。对于对象，assign_by_ref()函数也避免了对象的内存 拷贝。进一步的解释可以查看PHP手册的变量引用部分。

Example 13-4. assign_by_ref
例子13-4. 引用赋值

// passing name/value pairs
$smarty->assign_by_ref("Name",$myname);
$smarty->assign_by_ref("Address",$address);

Prev | Home | Next
assign 赋值 | Up | clear_all_assign 清除所有赋值


clear_all_assign

Prev Chapter 13. Methods Next

clear_all_assign
清除所有赋值

void clear_all_assign ()

This clears the values of all assigned variables.

清除所有已赋值到模板中的值。

Example 13-5. clear_all_assign
例子 13-5. 清除所有赋值

// clear all assigned variables
$smarty->clear_all_assign();

Prev | Home | Next
assign_by_ref 引用赋值 | Up | clear_all_cache 清除所有缓存


clear_all_cache

Prev Chapter 13. Methods Next

clear_all_cache
清除所有缓存

void clear_all_cache (int expire time)

This clears the entire template cache. As an optional parameter, you can supply a minimum age in seconds the cache files must be before they will get cleared.

清除所有模板缓存。作为可选参数“expire time”，你可以指定一个以秒为单位的最小时间，超过这个时间的缓存都将被清除掉。

Example 13-6. clear_all_cache
例子 13-6. 清除所有缓存

// clear the entire cache
$smarty->clear_all_cache();

Prev | Home | Next
clear_all_assign 清除所有赋值 | Up | clear_assign 清除赋值


clear_assign

Prev Chapter 13. Methods Next

clear_assign
清除赋值

void clear_assign (string var)

This clears the value of an assigned variable. This can be a single value, or an array of values.

清除指定模板变量的值。可以指定单独的一个变量名称，或者是一个数组。

Example 13-7. clear_assign
例子 13-7. 清除赋值

// clear a single variable
$smarty->clear_assign("Name");

// clear multiple variables
$smarty->clear_assign(array("Name","Address","Zip"));

Prev | Home | Next
clear_all_cache 清除所有缓存 | Up | clear_cache 清除缓存


clear_cache

Prev Chapter 13. Methods Next

clear_cache
清除缓存

void clear_cache (string template [, string cache id [, string compile id [, int expire time]]])

This clears the cache for a specific template. If you have multiple caches for this template, you can clear a specific cache by supplying the cache id as the second parameter. You can also pass a compile id as a third parameter. You can "group" templates together so they can be removed as a group. See the caching section for more information. As an optional fourth parameter, you can supply a minimum age in seconds the cache file must be before it will get cleared.

清除指定模板的缓存。如果这个模板有多个缓存，你可以用第二个参数指定要清除缓存的缓存号，还可以通过第三个参数指定编译号。你可以把模板分组，以 便可以方便的清除一组缓存。更多的信息可以查看缓存部分。第四个参数是可选的，用来指定超过某一 时间（以秒为单位）的缓存才会被清除。

Example 13-8. clear_cache
例子 13-8. 清除缓存

// clear the cache for a template
// 清除某一模板的缓存
$smarty->clear_cache("index.tpl");

// clear the cache for a particular cache id in an multiple-cache template
// 清除某一模板的多个缓存中指定缓存号的一个
$smarty->clear_cache("index.tpl","CACHEID");

Prev | Home | Next
clear_assign 清除赋值 | Up | clear_compiled_tpl 清除已编译模板


clear_compiled_tpl

Prev Chapter 13. Methods Next

clear_compiled_tpl
清除已编译模板

void clear_compiled_tpl (string tpl_file)

This clears the compiled version of the specified template resource, or all compiled template files if one is not specified. This function is for advanced use only, not normally needed.

清除指定模板资源的编译版本，如果不指定则清除所有已编译模板。除非特殊的需要，一般情况下不需要使用该函数。
（Fwolf:这个函数并不会删除模板本身，而是删除templates_c目录中存放的编译后生成的文件，这些编译后的文件会在下一次页面调用的时候再 一次被生成。）

Example 13-9. clear_compiled_tpl
例子 13-9. 清除已编译模板

// clear a specific template resource
// 清除指定模板资源的编译文件
$smarty->clear_compiled_tpl("index.tpl");

// clear entire compile directory
// 清除所有已编译的模板文件
$smarty->clear_compiled_tpl();

Prev | Home | Next
clear_cache 清除缓存 | Up | clear_config 清除配置


clear_config

Prev Chapter 13. Methods Next

clear_config
清除配置

void clear_config ([string var])

This clears all assigned config variables. If a variable name is supplied, only that variable is cleared.

清除所有配置变量，如果指定了变量名称，则只清除所指定的配置变量。

Example 13-10. clear_config
例子 13-10. 清除配置

// clear all assigned config variables.
// 清除所有配置变量
$smarty->clear_config();

// clear one variable
// 清除一个配置变量
$smarty->clear_config('foobar');

Prev | Home | Next
clear_compiled_tpl 清除已编译模板 | Up | config_load 加载配置


config_load

Prev Chapter 13. Methods Next

config_load
加载配置

void config_load (string file [, string section])

This loads config file data and assigns it to the template. This works identical to the template config_load function.

加载配置文件，并将其中的数据传送到模板中，它的功能和config_load函数是一样的。

Technical Note: As of Smarty 2.4.0, assigned template variables are kept across invocations of fetch() and display(). Config vars loaded from config_load() are always global scope. Config files are also compiled for faster execution, and respect the force_compile and compile_check settings.

注意：到Smarty 2.4.0为止，已赋值的模板变量对于fetch()和display()方法是共享调用的，而使用config_load()加载的变量是全局的。并且 在编译时配置文件也将被编译，以加快执行速度，并且遵守force_compile和compile_check设置。

Example 13-11. config_load
例子 13-11. 加载配置

// load config variables and assign them
// 加载配置变量
$smarty->config_load('my.conf');

// load a section
// 加载其中一节
$smarty->config_load('my.conf','foobar');

Prev | Home | Next
clear_config 清除配置 | Up | display 显示


display

Prev Chapter 13. Methods Next

display
显示

void display (string template [, string cache_id [, string compile_id]])

This displays the template. Supply a valid template resource type and path. As an optional second parameter, you can pass a cache id. See the caching section for more information.

显示模板，需要指定一个合法的模板资源的类型和路径。你还可以通过 第二个可选参数指定一个缓存号，相关的信息可以查看缓存。

As an optional third parameter, you can pass a compile id. This is in the event that you want to compile different versions of the same template, such as having separate templates compiled for different languages. Another use for compile_id is when you use more than one $template_dir but only one $compile_dir. Set a separate compile_id for each $template_dir, otherwise templates of the same name will overwrite each other. You can also set the $compile_id variable once instead of passing this to each call to display().

通过第三个可选参数，可以指定一个编译号。这在你想把一个模板编译成不同版本时使用，比如针对不同的语言编译模板。编译号的另外一个作用是，如果你 有多个$template_dir模板目录，但只有一个$compile_dir编译后存档目录，这时可以为每一个$template_dir模板目录指 定一个编译号，以避免相同的模板文件在编译后会互相覆盖。相对于在每一次调用display()的时候都指定编译号，也可以通过设置$compile_id编译号属性来一次性设定。

Example 13-12. display
例子 13-12. 显示

include("Smarty.class.php");
$smarty = new Smarty;
$smarty->caching = true;

// only do db calls if cache doesn't exist
// 只有在缓存不存在时才调用数据库
if(!$smarty->is_cached("index.tpl"))
{

 // dummy up some data
 $address = "245 N 50th";
 $db_data = array(
     "City" => "Lincoln",
     "State" => "Nebraska",
     "Zip" = > "68502"
     );

 $smarty->assign("Name","Fred");
 $smarty->assign("Address",$address);
 $smarty->assign($db_data);

}

// display the output
// 显示输出
$smarty->display("index.tpl");

Use the syntax for template resources to display files outside of the $template_dir directory.

通过模板资源的语法来使用不在$template_dir模板目录 下的文件。

Example 13-13. function display template resource examples
例子 13-13. 显示模板资源

// absolute filepath
// 绝对路径
$smarty->display("/usr/local/include/templates/header.tpl");

// absolute filepath (same thing)
// 绝对路径（另外一种方式）
$smarty->display("file:/usr/local/include/templates/header.tpl");

// windows absolute filepath (MUST use "file:" prefix)
// WINDOS平台下的绝对路径（必须使用“file:”前缀）
$smarty->display("file:C:/www/pub/templates/header.tpl");

// include from template resource named "db"
// 从模板资源“db“中调用
$smarty->display("db:header.tpl");

Prev | Home | Next
config_load 加载配置 | Up | fetch 取得输出的内容


fetch

Prev Chapter 13. Methods Next

fetch
取得输出的内容

string fetch (string template [, string cache_id [, string compile_id]])

This returns the template output instead of displaying it. Supply a valid template resource type and path. As an optional second parameter, you can pass a cache id. See the caching section for more information.

返回一个模板输出的内容（HTML代码），而不是直接显示出来，需要指定一个合法的模 板资源的类型和路径。你还可以通过 第二个可选参数指定一个缓存号，相关的信息可以查看缓存。

As an optional third parameter, you can pass a compile id. This is in the event that you want to compile different versions of the same template, such as having separate templates compiled for different languages. Another use for compile_id is when you use more than one $template_dir but only one $compile_dir. Set a separate compile_id for each $template_dir, otherwise templates of the same name will overwrite each other. You can also set the $compile_id variable once instead of passing this to each call to fetch().

通过第三个可选参数，可以指定一个编译号。这在你想把一个模板编译成不同版本时使用，比如针对不同的语言编译模板。编译号的另外一个作用是，如果你 有多个$template_dir模板目录，但只有一个$compile_dir编译后存档目录，这时可以为每一个$template_dir模板目录指 定一个编译号，以避免相同的模板文件在编译后会互相覆盖。相对于在每一次调用display()的时候都指定编译号，也可以通过设置$compile_id编 译号属性来一次性设定。

Example 13-14. fetch
例子 13-14. 取得输出的内容

include("Smarty.class.php");
$smarty = new Smarty;

$smarty->caching = true;

// only do db calls if cache doesn't exist
// 只有在缓存不存在时才调用数据库
if(!$smarty->is_cached("index.tpl"))
{

 // dummy up some data
 $address = "245 N 50th";
 $db_data = array(
     "City" => "Lincoln",
     "State" => "Nebraska",
     "Zip" = > "68502"
     );

 $smarty->assign("Name","Fred");
 $smarty->assign("Address",$address);
 $smarty->assign($db_data);

}

// capture the output
// 捕获输出
$output = $smarty->fetch("index.tpl");

// do something with $output here
// 对将要输出的内容进行处理

echo $output;

Prev | Home | Next
display 显示 | Up | get_config_vars 取配置变量的值


get_config_vars

Prev Chapter 13. Methods Next

get_config_vars
取配置变量的值

array get_config_vars ([string varname])

This returns the given loaded config variable value. If no parameter is given, an array of all loaded config variables is returned.

返回指定配置变量的值。如果不指定变量名称，则会返回一个包含所有已加载配置变量的值的数组。

Example 13-15. get_config_vars
例子 13-15. 取配置变量的值

// get loaded config template var 'foo'
// 得到已加载配置变量“foo”的值
$foo = $smarty->get_config_vars('foo');

// get all loaded config template vars
// 得到所有已加载配置变量的值
$config_vars = $smarty->get_config_vars();

// take a look at them
// 输出
print_r($config_vars);

Prev | Home | Next
fetch 取得输出的内容 | Up | get_registered_object 取得已注册的对象


get_registered_object

Prev Chapter 13. Methods Next

get_registered_object
取得已注册的对象

array get_registered_object (string object_name)

This returns a reference to a registered object. This is useful from within a custom function when you need direct access to a registered object.

返回一个已注册对象的引用。用于在一个自定义函数里直接调用已注册的对象。

Example 13-16. get_registered_object
例子 13-16. 取得已注册的对象

function smarty_block_foo($params, &$smarty) {
    if (isset[$params['object']]) {
        // get reference to registered object
                // 取得已注册对象的引用/地址
         $obj_ref =& $smarty->&get_registered_object($params['object']);
        // use $obj_ref is now a reference to the object
 // 现在就可以使用$obj_ref来直接调用对象了，它直接指向该对象，而不是一个拷贝
    }
}

Prev | Home | Next
get_config_vars 取得配置变量的值 | Up | get_template_vars 取得模板变量的值


get_template_vars

Prev Chapter 13. Methods Next

get_template_vars
取得模板变量的值

array get_template_vars ([string varname])

This returns the given assigned variable value. If no parameter is given, an array of all assigned variables is returned.

返回一个指定的已赋值的模板变量的值。如果不指定参数，则返回一个包含所有已赋值模板变量的值的数组。

Example 13-17. get_template_vars
例子 13-17. 取得模板变量的值

// get assigned template var 'foo'
$foo = $smarty->get_template_vars('foo');

// get all assigned template vars
$tpl_vars = $smarty->get_template_vars();

// take a look at them
print_r($tpl_vars);

Prev | Home | Next
get_registered_object 取得已注册的对象 | Up | is_cached 是否已被缓存


is_cached

Prev Chapter 13. Methods Next

is_cached
是否已被缓存

void is_cached (string template, [string cache_id])

This returns true if there is a valid cache for this template. This only works if caching is set to true.

在指定模板的缓存存在是返回真。只有在缓存设置为真时才可用。

Example 13-18. is_cached
例子 13-18. 是否已被缓存

$smarty->caching = true;

if(!$smarty->is_cached("index.tpl")) {
 // do database calls, assign vars here
 // 调用数据库，并对变量进行赋值
}

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

You can also pass a cache id as an an optional second parameter in case you want multiple caches for the given template.

如果模板有多个缓存的话，可以通过第二个可选参数指定缓存号。

Example 13-19. is_cached with multiple-cache template
例子 13-19. 多缓存模板的判断

$smarty->caching = true;

if(!$smarty->is_cached("index.tpl","FrontPage")) {
 // do database calls, assign vars here
}

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

Prev | Home | Next
get_template_vars 取得模板变量的值 | Up | load_filter 加载过滤器


load_filter

Prev Chapter 13. Methods Next

load_filter
加载过滤器

void load_filter (string type, string name)

This function can be used to load a filter plugin. The first argument specifies the type of the filter to load and can be one of the following: 'pre', 'post', or 'output'. The second argument specifies the name of the filter plugin, for example, 'trim'.

这个函数用来加载过滤器插件。第一个参数指定过滤器的类型，只能是下列之一：“pre”，“post”，或者是“output”。第二个参数指定过 滤器插件的名称，比如“trim”。

Example 13-20. loading filter plugins
例子 13-20. 加载过滤器插件

$smarty->load_filter('pre', 'trim'); // load prefilter named 'trim'
$smarty->load_filter('pre', 'datefooter'); // load another prefilter named 'datefooter'
$smarty->load_filter('output', 'compress'); // load output filter named 'compress'

Prev | Home | Next
is_cached 是否已被缓存 | Up | register_block 注册一个块


register_block

Prev Chapter 13. Methods Next

register_block
注册一个块

void register_block (string name, mixed impl, bool cacheable, array or null cache_attrs)

Use this to dynamically register block functions plugins. Pass in the block function name, followed by the PHP function callback that implements it.

用来动态注册/定义块函数插件。前两个参数指定块函数名称和执行函数的名称。

The php-function callback impl can be either (a) a string containing the function name or (b) an array of the form array(&$object, $method) with &$object being a reference to an object and $method being a string containing the mehod-name or (c) an array of the form array(&$class, $method) with $class being a classname and $method being a class method of that class.

执行函数的格式可以是一个包含函数名称的字符串；也可以是一个array(&$object, $method)数组形式，其中&$object是一个对象的引用，而$method是它的一个方法；还可以是一个array(&$ class, $method)数组形式，其中$class是一个类的名称，$method是类中的一个方法。

$cacheable and $cache_attrs can be omitted in most cases. See Controlling Cacheability of Plugins' Output on how to use them properly.

$cacheable 和 $cache_attrs 参数在大多数情况下可以省略。它们的使用方法可以查看控制插件输出的缓存。

Example 13-21. register_block
例子 13-21. 注册一个块

/* PHP */
$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}

Prev | Home | Next
load_filter 加载过滤器 | Up | register_compiler_function 注册编译函数


register_compiler_function

Prev Chapter 13. Methods Next

register_compiler_function
注册编译函数

void register_compiler_function (string name, mixed impl, bool cacheable)

Use this to dynamically register a compiler function plugin. Pass in the compiler function name, followed by the PHP function that implements it.

动态注册一个编译函数插件，前两个参数是编译函数的名称、执行函数的名称。

The php-function callback impl can be either (a) a string containing the function name or (b) an array of the form array(&$object, $method) with &$object being a reference to an object and $method being a string containing the mehod-name or (c) an array of the form array(&$class, $method) with $class being a classname and $method being a class method of that class.

执行函数的格式可以是一个包含函数名称的字符串；也可以是一个array(&$object, $method)数组形式，其中&$object是一个对象的引用，而$method是它的一个方法；还可以是一个array(&$ class, $method)数组形式，其中$class是一个类的名称，$method是类中的一个方法。

$cacheable can be omitted in most cases. See Controlling Cacheability of Plugins' Output on how to it properly.

$cacheable 参数在大多数情况下可以省略。具体的使用方法可以查看控 制插件输出的缓存。

Prev | Home | Next
register_block 注册一个块 | Up | register_function 注册函数


register_function

Prev Chapter 13. Methods Next

register_function
注册函数

void register_function (string name, mixed impl, bool cacheable, array or null cache_attrs)

Use this to dynamically register template function plugins. Pass in the template function name, followed by the PHP function name that implements it.

动态注册模板函数插件，前两个参数是模板函数名称和执行函数名称。

The php-function callback impl can be either (a) a string containing the function name or (b) an array of the form array(&$object, $method) with &$object being a reference to an object and $method being a string containing the mehod-name or (c) an array of the form array(&$class, $method) with $class being a classname and $method being a class method of that class.

执行函数的格式可以是一个包含函数名称的字符串；也可以是一个array(&$object, $method)数组形式，其中&$object是一个对象的引用，而$method是它的一个方法；还可以是一个array(&$ class, $method)数组形式，其中$class是一个类的名称，$method是类中的一个方法。

$cacheable and $cache_attrs can be omitted in most cases. See Controlling Cacheability of Plugins' Output on how to use them properly.

$cacheable 和 $cache_attrs 参数在大多数情况下可以省略。它们的使用方法可以查看控 制插件输出的缓存。

Example 13-22. register_function
例子 13-22. 注册函数

$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());
}

// now you can use this in Smarty to print the current date: {date_now}
// or, {date_now format="%Y/%m/%d"} to format it.

// 现在你可以在模板中这样显示日期：{date_now}
// 或者用{date_now format="%Y/%m/%d"}的格式进行格式化

Prev | Home | Next
register_compiler_function 注册编译函数 | Up | register_modifier 注册修饰器


register_modifier

Prev Chapter 13. Methods Next

register_modifier
注册修饰器

void register_modifier (string name, mixed impl)

Use this to dynamically register modifier plugin. Pass in the template modifier name, followed by the PHP function that it implements it.

动态注册一个修饰器插件，需要制定模板修饰器的名称，和实现具体功能的函数。

The php-function callback impl can be either (a) a string containing the function name or (b) an array of the form array(&$object, $method) with &$object being a reference to an object and $method being a string containing the mehod-name or (c) an array of the form array(&$class, $method) with $class being a classname and $method being a class method of that class.

执行函数的格式可以是一个包含函数名称的字符串；也可以是一个array(&$object, $method)数组形式，其中&$object是一个对象的引用，而$method是它的一个方法；还可以是一个array(&$ class, $method)数组形式，其中$class是一个类的名称，$method是类中的一个方法。

Example 13-23. register_modifier
例子 13-23. 注册修饰器

// let's map PHP's stripslashes function to a Smarty modifier.
// 把PHP的stripslashes函数影像为Smarty模板的修饰器

$smarty->register_modifier("sslash","stripslashes");

// now you can use {$var|sslash} to strip slashes from variables
// 现在可以在模板中使用{$var|sslash}的格式来去除变量中的特殊符号了

Prev | Home | Next
register_function 注册函数 | Up | register_object 注册对象


register_object

Prev Chapter 13. Methods Next

register_object
注册对象

void register_object (string object_name, object $object, array allowed methods/properties, boolean format, array block methods)

This is to register an object for use in the templates. See the object section of the manual for examples.

注册一个在模板中使用的对象，相关的例子在手册的对象小节中。

Prev | Home | Next
register_modifier 注册修饰器 | Up | register_outputfilter 注册输出过滤器


register_outputfilter

Prev Chapter 13. Methods Next

register_outputfilter
注册输出过滤器

void register_outputfilter (mixed function)

Use this to dynamically register outputfilters to operate on a template's output before it is displayed. See template output filters for more information on how to set up an output filter function.

动态注册一个输出过滤器，以便在模板输出之前进行操作。如何设立输出过滤函数，请查看模板输出过滤。

The php-function callback function can be either (a) a string containing the function name or (b) an array of the form array(&$object, $method) with &$object being a reference to an object and $method being a string containing the mehod-name or (c) an array of the form array(&$class, $method) with $class being a classname and $method being a class method of that class.

执行函数的格式可以是一个包含函数名称的字符串；也可以是一个array(&$object, $method)数组形式，其中&$object是一个对象的引用，而$method是它的一个方法；还可以是一个array(&$ class, $method)数组形式，其中$class是一个类的名称，$method是类中的一个方法。

Prev | Home | Next
register_object 注册对象 | Up | register_postfilter 注册提交过滤器


register_postfilter

Prev Chapter 13. Methods Next

register_postfilter
注册提交过滤器

void register_postfilter (mixed function)

Use this to dynamically register postfilters to run templates through after they are compiled. See template postfilters for more information on how to setup a postfiltering function.

动态注册一个在模板编译之后执行的提交过滤器。如何设立提交过滤函数，请查看模板提交过滤器。

The php-function callback function can be either (a) a string containing the function name or (b) an array of the form array(&$object, $method) with &$object being a reference to an object and $method being a string containing the mehod-name or (c) an array of the form array(&$class, $method) with $class being a classname and $method being a class method of that class.

执行函数的格式可以是一个包含函数名称的字符串；也可以是一个array(&$object, $method)数组形式，其中&$object是一个对象的引用，而$method是它的一个方法；还可以是一个array(&$ class, $method)数组形式，其中$class是一个类的名称，$method是类中的一个方法。

Prev | Home | Next
register_outputfilter 注册输出过滤器 | Up | register_prefilter 注册预过滤器


register_prefilter

Prev Chapter 13. Methods Next

register_prefilter
注册预过滤器

void register_prefilter (mixed function)

Use this to dynamically register prefilters to run templates through before they are compiled. See template prefilters for more information on how to setup a prefiltering function.

注册一个在模板编译之前执行的预过滤器。如何设立预过滤函数，请查看模板预过滤器。

The php-function callback function can be either (a) a string containing the function name or (b) an array of the form array(&$object, $method) with &$object being a reference to an object and $method being a string containing the mehod-name or (c) an array of the form array(&$class, $method) with $class being a classname and $method being a class method of that class.

执行函数的格式可以是一个包含函数名称的字符串；也可以是一个array(&$object, $method)数组形式，其中&$object是一个对象的引用，而$method是它的一个方法；还可以是一个array(&$ class, $method)数组形式，其中$class是一个类的名称，$method是类中的一个方法。

Prev | Home | Next
register_postfilter 注册提交过滤器 | Up | register_resource 注册资源


register_resource

Prev Chapter 13. Methods Next

register_resource
注册资源

void register_resource (string name, array resource_funcs)

Use this to dynamically register a resource plugin with Smarty. Pass in the name of the resource and the array of PHP functions implementing it. See template resources for more information on how to setup a function for fetching templates.

动态注册一个资源插件，前两个参数是资源的名称和执行函数的数组。关于如何建立一个函数取出模板，请看模板资源部分。

Technical Note: A resource name must be at least two characters in length. One character resource names will be ignored and used as part of the file path, such as $smarty->display('c:/path/to/index.tpl');

注意：资源的名称主要要有两个字符组成。一个字符的资源名 称将被忽略，并被视为是文件路径的一部分，比如$smarty->display('c:/path/to/index.tpl');。

The php-function-array resource_funcs must have 4 or 5 elements. With 4 elements the elements are the functions-callbacks for the respective "source", "timestamp", "secure" and "trusted" functions of the resource. With 5 elements the first element has to be an object reference or a class name of the object or class implementing the resource and the 4 following elements have to be the method names implementing "source", "timestamp", "secure" and "trusted".

执行函数数组必须包含4或5个元素。包含4个元素的情况下，这些函数分别是处理“source 源文本”、“timestamp 时间戳”、“secure 安全”、“trusted 可信的”的函数。5个元素的情况下，第一个元素必须是一个对象的引用，或者是一个类名，后面的4个元素是实现处理“source 源文本”、“timestamp 时间戳”、“secure 安全”、“trusted 可信的”的方法。

Example 13-24. register_resource
例子 13-24. 注册资源

$smarty->register_resource("db", array("db_get_template",
 "db_get_timestamp",
 "db_get_secure",
 "db_get_trusted"));

Prev | Home | Next
register_prefilter 注册预过滤器 | Up | trigger_error 触发错误


trigger_error

Prev Chapter 13. Methods Next

trigger_error
触发错误

void trigger_error (string error_msg, [int level])

This function can be used to output an error message using Smarty. level parameter can be one of the values used for trigger_error() PHP function, i.e. E_USER_NOTICE, E_USER_WARNING, etc. By default it's E_USER_WARNING.

用来使用Smarty内置的方法输出错误信息。参数level可 以是PHP函数trigger_error()的一个参数值，如E_USER_NOTICE, E_USER_WARNING等，一般默认为E_USER_WARNING。

Prev | Home | Next
register_resource 注册资源 | Up | template_exists 模板是否存在


template_exists

Prev Chapter 13. Methods Next

template_exists
模板是否存在

bool template_exists (string template)

This function checks whether the specified template exists. It can accept either a path to the template on the filesystem or a resource string specifying the template.

检查制定的模板是否存在，参数template既可以是模板的文件路径，也可以是指定的资源字符串。

Prev | Home | Next
trigger_error 触发错误 | Up | unregister_block 注销一个块


unregister_block

Prev Chapter 13. Methods Next

unregister_block
注销一个块

void unregister_block (string name)

Use this to dynamically unregister block function plugin. Pass in the block function name.

动态注销一个块函数插件，参数是块函数的名称。

Prev | Home | Next
template_exists 模板是否存在 | Up | unregister_compiler_function 注销编译函数


unregister_compiler_function

Prev Chapter 13. Methods Next

unregister_compiler_function
注销编译函数

void unregister_compiler_function (string name)

Use this to dynamically unregister a compiler function. Pass in the name of the compiler function.

动态注销一个编译函数，参数name是编译函数的名称。

Prev | Home | Next
unregister_block 注销块 | Up | unregister_function 注销函数


unregister_function

Prev Chapter 13. Methods Next

unregister_function
注销函数

void unregister_function (string name)

Use this to dynamically unregister template function plugin. Pass in the template function name.

动态注销一个模板函数插件，参数是模板函数的名称。

Example 13-25. unregister_function
例子 13-35. 注销函数

// we don't want template designers to have access to system files
// 让模板设计者不能操作系统文件

$smarty->unregister_function("fetch");

Prev | Home | Next
unregister_compiler_function 注销编译函数 | Up | unregister_modifier 注销修饰器


unregister_modifier

Prev Chapter 13. Methods Next

unregister_modifier
注销修饰器

void unregister_modifier (string name)

Use this to dynamically unregister modifier plugin. Pass in the template modifier name.

动态注销修饰器插件，参数是模板修饰器的名称。

Example 13-26. unregister_modifier
例子 13-26. 注销修饰器

// we don't want template designers to strip tags from elements
// 禁止模板设计者去除元素的标记

$smarty->unregister_modifier("strip_tags");

Prev | Home | Next
unregister_function 注销函数 | Up | unregister_object 注销对象


unregister_object

Prev Chapter 13. Methods Next

unregister_object
注销对象

void unregister_object (string object_name)

Use this to unregister an object.

注销一个对象。

Prev | Home | Next
unregister_modifier 注销修饰器 | Up | unregister_outputfilter 注销输出过滤器


unregister_outputfilter

Prev Chapter 13. Methods Next

unregister_outputfilter
注销输出过滤器

void unregister_outputfilter (string function_name)

Use this to dynamically unregister an output filter.

动态注销一个输出过滤器。

Prev | Home | Next
unregister_object 注销对象 | Up | unregister_postfilter 注销提交过滤器


unregister_postfilter

Prev Chapter 13. Methods Next

unregister_postfilter
注销提交过滤器

void unregister_postfilter (string function_name)

Use this to dynamically unregister a postfilter.

动态注销提交过滤器（在模板编译完成后执行）。

Prev | Home | Next
unregister_outputfilter 注销输出过滤器 | Up | unregister_prefilter 注销预过滤器


unregister_prefilter

Prev Chapter 13. Methods Next

unregister_prefilter
注销预过滤器

void unregister_prefilter (string function_name)

Use this to dynamically unregister a prefilter.

动态注销一个预过滤器（模板编译前执行）。

Prev | Home | Next
unregister_postfilter 注销提交过滤器 | Up | unregister_resource 注销资源


unregister_resource

Prev Chapter 13. Methods Next

unregister_resource
注销资源

void unregister_resource (string name)

Use this to dynamically unregister a resource plugin. Pass in the name of the resource.

动态注销一个资源插件，参数是资源的名称。

Example 13-27. unregister_resource
例子 13-27. 注销资源

$smarty->unregister_resource("db");

Prev | Home | Next
unregister_prefilter 注销预过滤器 | Up | Caching 缓存


Caching

Prev Next

Chapter 14. Caching [缓存]

Table of Contents [内容列表]
Setting Up Caching [建立缓存]
Multiple Caches Per Page [每页多个缓存]
Cache Groups [缓存集合]
Controlling Cacheability of Plugins' Output [控制插件输出的缓冲能力]

Caching is used to speed up a call to display() or fetch() by saving its output to a file. If a cached version of the call is available, that is displayed instead of regenerating the output. Caching can speed things up tremendously, especially templates with longer computation times. Since the output of display() or fetch() is cached, one cache file could conceivably be made up of several template files, config files, etc.
缓存被用来保存一个文档的输出从而加速display()或fetch()函数的执行。如果一个函数被加进缓存，那么实际输出的内容将用缓存来代替。缓存可让事物非常快速的执行，特别是带有长计算时间的模板。一旦display()或fetch()用缓存输出，那么一个缓存文档将非常容易用几个模板文档或是配置文档等来组成〔功力不小〕。

Since templates are dynamic, it is important to be careful what you are caching and for how long. For instance, if you are displaying the front page of your website that does not change its content very often, it might work well to cache this page for an hour or more. On the other hand, if you are displaying a page with a weather map containing new information by the minute, it would not make sense to cache this page.
一旦模板是动态〔应该不难理解〕的，哪些文档你加了缓存，缓存时间多长都是很重要的。举个例子，比如你站点的首页内容不是经常更改，那么对首页缓存一个小时或是更长都可得到很好效果。相反，几分钟就要更新一下信息的天气地图页面，用缓存就不好了。

Setting Up Caching [建立缓存]

The first thing to do is enable caching. This is done by setting $caching = true (or 1.)
首先要做的就是让缓存可用。这就要设置$caching = true(或 1.)

Example 14-1. enabling caching
例14-1.使缓存可用

require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching = true;

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

With caching enabled, the function call to display('index.tpl') will render the template as usual, but also saves a copy of its output to a file (a cached copy) in the $cache_dir. Upon the next call to display('index.tpl'), the cached copy will be used instead of rendering the template again.
建立缓存后，display('index.tpl')函数会把模板返回原来状态〔没缓存〕，也会把输出保存copy〖n.名词〗到$cache_dir.下次调用display('index.tpl')，保存的缓存copy〖n.〗会被再用来代替原来的模板。

Technical Note: The files in the $cache_dir are named similar to the template name. Although they end in the ".php" extention, they are not really executable php scripts. Do not edit these files!
技术提示：在$chche_dir目录里的文档命名跟模板一致。尽管是用.php作为扩展名，但并不会被当作php代码来解析。所以不要去修改它。

Each cached page has a limited lifetime determined by $cache_lifetime. The default value is 3600 seconds, or 1 hour. After that time expires, the cache is regenerated. It is possible to give individual caches their own expiration time by setting $caching = 2. See the documentation on $cache_lifetime for details.
每个缓存页都有一个用$cache_lifetime来控制的会话期。初始值是3600秒，就是一小时〔废话嘛〕。会话期结束，缓存就会重建。你可以通过设置$caching=2来控制单个缓存文件各自的的过期时间。祥细内容察看$cache_lifetime里面的列表。

Example 14-2. setting cache_lifetime per cache
例14-2 设置单个缓存会话期〔时间〕

require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching = 2; // lifetime is per cache

// set the cache_lifetime for index.tpl to 5 minutes
$smarty->cache_lifetime = 300;
$smarty->display('index.tpl');

// set the cache_lifetime for home.tpl to 1 hour
$smarty->cache_lifetime = 3600;
$smarty->display('home.tpl');

// NOTE: the following $cache_lifetime setting will not work when $caching = 2.
//提示：在$chching=2后面的$chche_lifetime不会起作用。
// The cache lifetime for home.tpl has already been set
// to 1 hour, and will no longer respect the value of $cache_lifetime.
// home.tpl的缓存会话期设为1小时后，不会再按$cache_lifetime的值改变。
// The home.tpl cache will still expire after 1 hour.
// home.tpl的缓存会在1小时后结束。$smarty->cache_lifetime = 30; // 30 seconds
$smarty->display('home.tpl');

If $compile_check is enabled, every template file and config file that is involved with the cache file is checked for modification. If any of the files have been modified since the cache was generated, the cache is immediately regenerated. This is a slight overhead so for optimum performance, leave $compile_check set to false.
如果$compile_check可用，每个跟缓存文档相关的模板文档和配置文档都会被检查来确定是否需要修改。在缓存产生后，改动任何文档，缓存也跟着更新改动。设置$compile_check为false，这是实现最佳性能的最小改动〔应该是这样:D〕。

Example 14-3. enabling $compile_check
例14-3.可用$compile_check

require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching = true;
$smarty->compile_check = true;

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

If $force_compile is enabled, the cache files will always be regenerated. This effectively turns off caching. $force_compile is usually for debugging purposes only, a more efficient way of disabling caching is to set $caching = false (or 0.)
一旦$force_compile可用，缓存文档会一直重建。这有效地关闭缓存。$force_compile只是用来调试，更有效关闭缓存的方法是让$caching = false(或0.)

The is_cached() function can be used to test if a template has a valid cache or not. If you have a cached template that requires something like a database fetch, you can use this to skip that process.
is_cached()函数可用来测试一个模板是否有有效的缓存。如果一个缓存模板需要从数据库中获取数据，可以用这个函数来跳过这个过程。

Example 14-4. using is_cached()
例14-4.使用is_cached()

require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching = true;

if(!$smarty->is_cached('index.tpl')) {
    // No cache available, do variable assignments here.
    $contents = get_database_contents();
    $smarty->assign($contents);
}

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

You can keep parts of a page dynamic with the insert template function. Let's say the whole page can be cached except for a banner that is displayed down the right side of the page. By using an insert function for the banner, you can keep this element dynamic within the cached content. See the documentation on insert for details and examples.
你可以插入模板函数insert来使部分页面动态化。除了在右下方显示的标语外整个页面都可以缓存。在缓存内容里面可以插入函数来使标语也动态化。查看相关文档关于insert的细节和例子。

You can clear all the cache files with the clear_all_cache() function, or individual cache files (or groups) with the clear_cache() function.
你可以用clear_all_cache()来清除所有缓存，或用clear_cache()来清除单个缓存文档。

Example 14-5. clearing the cache
例14-5.清除缓存

require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching = true;

// clear out all cache files
$smarty->clear_all_cache();

// clear only cache for index.tpl
$smarty->clear_cache('index.tpl');

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

Prev | Home | Next
unregister_resource 注销资源 | Up | Multiple Caches Per Page 每页多个缓存


Multiple Caches Per Page

Prev Chapter 14. Caching Next

Multiple Caches Per Page 每页多个缓存

You can have multiple cache files for a single call to display() or fetch(). Let's say that a call to display('index.tpl') may have several different output contents depending on some condition, and you want separate caches for each one. You can do this by passing a cache_id as the second parameter to the function call.
你可以用单个函数display()或fetch()来输出多个缓存文档。display('index.tpl')在多种条件下会有不同的输出内容，要单独的把缓存分开。可以通过函数的第二参数cache_id来达到效果。

Example 14-6. passing a cache_id to display()
例14-6.传给display()一个cache_id

require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching = true;

$my_cache_id = $_GET['article_id'];

$smarty->display('index.tpl',$my_cache_id);

Above, we are passing the variable $my_cache_id to display() as the cache_id. For each unique value of $my_cache_id, a separate cache will be generated for index.tpl. In this example, "article_id" was passed in the URL and is used as the cache_id.
上面，我们通过变量$my_cache_id作为cache_id来display()。在index.tpl里$my_cache_id的每个唯一值，会建立单独的缓存。在这个例子里，"article_id"在URL传送，并用作cache_id。

Technical Note: Be very cautious when passing values from a client (web browser) into Smarty (or any PHP application.) Although the above example of using the article_id from the URL looks handy, it could have bad consequences. The cache_id is used to create a directory on the file system, so if the user decided to pass an extremely large value for article_id, or write a script that sends random article_ids at a rapid pace, this could possibly cause problems at the server level. Be sure to sanitize any data passed in before using it. In this instance, maybe you know the article_id has a length of 10 characters and is made up of alpha-numerics only, and must be a valid article_id in the database. Check for this!
技术提示：要注意从客户端(web浏览器)传值到Smarty(或任何PHP应用程序)的过程。尽管上面的例子用article_id从URL传值看起来很方便，却可能有糟糕的后果[安全问题]。cache_id被用来在文件系统里创建目录，如果用户想为article_id赋一个很大的值，或写一些代码来快速发送随机的article_ids，就有可能会使服务器出现问题。确定在使用它之前清空已存在的数据。在这个例子，可能你知道article_id的长度(值吧？！)是10字符，并只由字符-数字组成，在数据库里是个可用的article_id。Check for this!要注意检查这个问题！〔要注意这个提示!不用再说了吧？〕

Be sure to pass the same cache_id as the second parameter to is_cached() and clear_cache().
确定传给is_cached()和clear_cache()的第二参数是同一个cache_id。

Example 14-7. passing a cache_id to is_cached()
例14-7.传给is_cached()一个cache_id

require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching = true;

$my_cache_id = $_GET['article_id'];

if(!$smarty->is_cached('index.tpl',$my_cache_id)) {
    // No cache available, do variable assignments here.
    $contents = get_database_contents();
    $smarty->assign($contents);
}

$smarty->display('index.tpl',$my_cache_id);

You can clear all caches for a particular cache_id by passing null as the first parameter to clear_cache().
你可以通过把clear_cache()的第一参数设为null来为特定的cache_id清除所有缓存。

Example 14-8. clearing all caches for a particular cache_id
例14-8.为特定的cache_id清除所有缓存

require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching = true;

// clear all caches with "sports" as the cache_id
$smarty->clear_cache(null,"sports");

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

In this manner, you can "group" your caches together by giving them the same cache_id.
通过这种方式，你可以用相同的cache_id来把你的缓存集合起来。

Prev | Home | Next
Caching 缓存 | Up | Cache Groups 缓存集合


Cache Groups

Prev Chapter 14. Caching Next

Cache Groups [缓存集合]

You can do more elaborate grouping by setting up cache_id groups. This is accomplished by separating each sub-group with a vertical bar "|" in the cache_id value. You can have as many sub-groups as you like.
你可以通过建立cache_id集合做更祥细的集合体。在cache_id的值里用竖线"|"来分开子集合。你可以尽可能多的包含子集合。

Example 14-9. cache_id groups
例14-9.cache_id集合

require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching = true;

// clear all caches with "sports|basketball" as the first two cache_id groups
$smarty->clear_cache(null,"sports|basketball");

// clear all caches with "sports" as the first cache_id group. This would
// include "sports|basketball", or "sports|(anything)|(anything)|(anything)|..."
$smarty->clear_cache(null,"sports");

$smarty->display('index.tpl',"sports|basketball");

Technical Note: The cache grouping does NOT use the path to the template as any part of the cache_id. For example, if you have display('themes/blue/index.tpl'), you cannot clear the cache for everything under the "themes/blue" directory. If you want to do that, you must group them in the cache_id, such as display('themes/blue/index.tpl','themes|blue'); Then you can clear the caches for the blue theme with clear_cache(null,'themes|blue');
技术提示:缓存集合并不像cache_id一样对模板使用路径。比如，如果你display('themes/blue/index.tpl'),那么在"themes/blue"目录下你并不能清除缓存。想要清除缓存，必须先用cache_id把缓存集合，像这样display('themes/blue/index.tpl','themes|blue')；然后就可以用clear_cache(null,'themes|blue')清除blue theme(蓝色主题？！老外也真会叫...)下的缓存。

Prev | Home | Next
Multiple Caches Per Page [每页多个缓存] | Up | Controlling Cacheability of Plugins' Output [高级特征]


Controlling Cacheability of Plugins' Output

Prev Chapter 14. Caching Next

Controlling Cacheability of Plugins' Output控制插件输出的缓冲能力

Since Smarty-2.6.0 plugins the cacheability of plugins can be declared when registering them. The third parameter to register_block, register_compiler_function and register_function is called $cacheable and defaults to true which is also the behaviour of plugins in Smarty versions before 2.6.0

自从Smarty-2.6.0插件以来，如果注册它们，则插件的缓存能力能够被重新声明的。register_block，register_compiler_function 和register_function的第3个参数就是$ cacheable , 并且它的值默认为true。当然，在2.6.0版本之前它的默认值也是这样的。

When registering a plugin with $cacheable=false the plugin is called everytime the page is displayed, even if the page comes from the cache. The plugin function behaves a little like an insert function.

当用$cacheable=false来这册一个插件，则每次这个页面被输出的时候，这个插件就会被使用，即使这个页面来自缓存。这个插件函数的行为有点像这个函数insert。

In contrast to {insert} the attributes to the plugins are not cached by default. They can be declared to be cached with the fourth parameter $cache_attrs . $cache_attrs is an array of attribute-names that should be cached, so the plugin-function get value as it was the time the page was written to cache everytime it is fetched from the cache.

和{insert}相反，插件的属性默认是不缓存的。通过使用第四个参数 $cache_attrs ，它们能够被重新声明为缓存的。 $cache_attrs 是一个属性名字的数组，可以被缓存，所以每次当它被从缓存中取出的时候，这个插件函数获得值-----因为这个页面会被写入用来缓存。

Example 14-10. Preventing a plugin's output from being cached

例14-10.阻止插件从缓存中输出

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;

function remaining_seconds($params, &$smarty) {
 $remain = $params['endtime'] - time();
 if ($remain >=0)
 return $remain . " second(s)";
 else
 return "done";
}

$smarty->register_function('remaining', 'remaining_seconds', false, array('endtime'));

if (!$smarty->is_cached('index.tpl')) {
 // fetch $obj from db and assign...
 $smarty->assign_by_ref('obj', $obj);
}

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

index.tpl:

Time Remaining: {remain endtime=$obj->endtime}

The number of seconds till the endtime of $obj is reached changes on each display of the page, even if the page is cached. Since the endtime attribute is cached the object only has to be pulled from the database when page is written to the cache but not on subsequent requests of the page.

直到$obj运行结束，时间的秒数在每一个页面输出的时候会改变，即使这个页面被缓存。只要结束时间属性被缓存，当页面被写入到缓存但是没有对这个页面接着的请求的时候对象只是不得不重新从数据库里取出而已。

Example 14-11. Preventing a whole passage of a template from being cached

例14-11.阻止一个模板文件的 整篇被缓存

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;

function smarty_block_dynamic($param, $content, &$smarty) {
 return $content;
}
$smarty->register_block('dynamic', 'smarty_block_dynamic', false);

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

index.tpl:

Page created: {"0"|date_format:"%D %H:%M:%S"}

{dynamic}

Now is: {"0"|date_format:"%D %H:%M:%S"}

... do other stuff ...

{/dynamic}

When reloading the page you will notice that both dates differ. One is "dynamic" one is "static". You can do everything between {dynamic}...{/dynamic} and be sure it will not be cached like the rest of the page.

当重新加载这个页面，你将会注意到这两个日期不同。一个是“动态“，一个是“静态”。你能够在{dynamic}...{/dynamic}之间作任何事情，并且保证它将不会像剩下的页面一样被缓存。

Prev | Home | Next
Cache Groups [缓存集合] | Up | Advanced Features [高级特征]


Advanced Features

Prev Next

Chapter 15. Advanced Features

高级特点

Table of Contents
Objects 对象
Prefilters 预过滤器
Postfilters 后过滤器
Output Filters 输出过滤器
Cache Handler Function 缓冲处理函数
Resources 资源

Objects

对象

Smarty allows access to PHP objects through the templates. There are two ways to access them. One way is to register objects to the template, then use access them via syntax similar to custom functions. The other way is to assign objects to the templates and access them much like any other assigned variable. The first method has a much nicer template syntax. It is also more secure, as a registered object can be restricted to certain methods or properties. However, a registered object cannot be looped over or assigned in arrays of objects, etc. The method you choose will be determined by your needs, but use the first method whenever possible to keep template syntax to a minimum.

SMARTY允许通过模板访问PHP对象。有两种方式来访问它们。一种是注册对象到模板，然后通过类似于用户自定义函数的形式来访问它。另一种方法给模板分配对象,然后通过访问其它赋值变量类似的方法进行访问。第一种方法有一个很好的模板语法，同时它作为一个注册对象被限制为几个固定的方法和目标，这样是比较安全的。然而一个注册对象不能够在相对自身数组里面循环使用和赋值。总之，你根据你自己的需求来觉得选用那种方法，但是使用第一种方法的话，可以让你的模伴语法达到最小。

If security is enabled, no private methods or functions can be accessed (begininning with "_"). If a method and property of the same name exist, the method will be used.

如果安全选项激活后，就没有私有成员或者函数能够被访问（以"_"开头）。如果有一个同名成员或者对象存在，那么方法将被使用。

You can restrict the methods and properties that can be accessed by listing them in an array as the third registration parameter.

你可以限制成员和函数，但是外解可以通过列举它们为一个第三注册变量的数组的方式来访问它。

By default, parameters passed to objects through the templates are passed the same way custom functions get them. An associative array is passed as the first parameter, and the smarty object as the second. If you want the parameters passed one at a time for each argument like traditional object parameter passing, set the fourth registration parameter to false.

一般情况下，参数通过模板传递给对象的方法和自定义函数获得参数的方法是一样的。一个混合数组作为第一个参数传递，而SMARTY对象作为第二个。如果你想像传统的对象参数一样一次传递一个参数，设置第四个参数为 FALSE即可。

Example 15-1. using a registered or assigned object

<?php
// the object

class My_Object() {
    function meth1($params, &$smarty_obj) {
        return "this is my meth1";
    }
}

$myobj = new My_Object;
// registering the object (will be by reference)
$smarty->register_object("foobar",$myobj);
// if we want to restrict access to certain methods or properties, list them
$smarty->register_object("foobar",$myobj,array('meth1','meth2','prop1'));
// if you want to use the traditional object parameter format, pass a boolean of false
$smarty->register_object("foobar",$myobj,null,false);

// We can also assign objects. Assign by ref when possible.
$smarty->assign_by_ref("myobj", $myobj);

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

TEMPLATE:

{* access our registered object *}
{foobar->meth1 p1="foo" p2=$bar}

{* you can also assign the output *}
{foobar->meth1 p1="foo" p2=$bar assign="output"}
the output was {$output)

{* access our assigned object *}
{$myobj->meth1("foo",$bar)}

Prev | Home | Next
Cache Groups | Up | Prefilters


Prefilters

预过滤器

Template prefilters are PHP functions that your templates are ran through before they are compiled. This is good for preprocessing your templates to remove unwanted comments, keeping an eye on what people are putting in their templates, etc. Prefilters can be either registered or loaded from the plugins directory by using load_filter() function or by setting $autoload_filters variable. Smarty will pass the template source code as the first argument, and expect the function to return the resulting template source code.

模板后过滤器是一些PHP函数，模板就是在那些函数编译后才运行。这样有利于预先处理你的模板，删除不不需要的内容，监视对模板进行的操作，例如：预过滤器同样能够通过 load filter() 函数和设置 $autoload filters 变量来注册或者从工具目录里载入。SMARTY将传递模板输出作为第一个参数，通过自定义函数返回处理结果。

Example 15-2. using a template prefilter

<?php
// put this in your application
function remove_dw_comments($tpl_source, &$smarty)
{
 return preg_replace("/<!--#.*-->/U","",$tpl_source);
}

// register the prefilter
$smarty->register_prefilter("remove_dw_comments");
$smarty->display("index.tpl");
?>

{* Smarty template index.tpl *}
<!--# this line will get removed by the prefilter -->

Prev | Home | Next
Advanced Features | Up | Postfilters


Postfilters

后过滤器

Template postfilters are PHP functions that your templates are ran through after they are compiled. Postfilters can be either registered or loaded from the plugins directory by using load_filter() function or by setting $autoload_filters variable. Smarty will pass the compiled template code as the first argument, and expect the function to return the result of the processing.

模板后过滤器是一些PHP函数，模板就是在那些函数编译后才运行。后过滤器同样能够通过 load filter() 函数和设置 $autoload filters 变量来注册或者从工具目录里载入。SMARTY将传递模板输出作为第一个参数，通过自定义函数返回处理结果。

Example 15-3. using a template postfilter

<?php
// put this in your application
function add_header_comment($tpl_source, &$smarty)
{
 return "<?php echo \"<!-- Created by Smarty! -->\n\" ?>\n".$tpl_source;
}

// register the postfilter
$smarty->register_postfilter("add_header_comment");
$smarty->display("index.tpl");
?>

{* compiled Smarty template index.tpl *}
<!-- Created by Smarty! -->
{* rest of template content... *}

Prev | Home | Next
Prefilters | Up | Output Filters


Output Filters

输出滤镜

When the template is invoked via display() or fetch(), its output can be sent through one or more output filters. This differs from postfilters because postfilters operate on compiled templates before they are saved to the disk, and output filters operate on the template output when it is executed.

当模板通过函数 display() 或者 fetch()被调用时，它的输出能够通过一个或者多个滤镜而发出。 它与预过滤器的不同之处就是预过滤器编译模板是在模板保存到磁盘之前，输出滤镜是在它执行的时候才操作模板输出的。

Output filters can be either registered or loaded from the plugins directory by using load_filter() function or by setting $autoload_filters variable. Smarty will pass the template output as the first argument, and expect the function to return the result of the processing.

输出滤镜同样能够通过 load filter() 函数和设置 $autoload filters 变量来注册或者从工具目录里载入。SMARTY将传递模板输出作为第一个参数，通过自定义函数返回处理结果。

Example 15-4. using a template outputfilter

<?php
// put this in your application
function protect_email($tpl_output, &$smarty)
{
 $tpl_output =
 preg_replace('!(\S+)@([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,3}|[0-9]{1,3}))!',
 '$1%40$2', $tpl_output);
 return $tpl_output;
}

// register the outputfilter
$smarty->register_outputfilter("protect_email");
$smarty->display("index.tpl");

// now any occurrence of an email address in the template output will have
// a simple protection against spambots
?>

Prev | Home | Next
Postfilters | Up | Cache Handler Function


Cache Handler Function

缓冲处理函数

As an alternative to using the default file-based caching mechanism, you can specify a custom cache handling function that will be used to read, write and clear cached files.

作为一个可选择使用的默认基于文本的缓冲机制，你可以定制或者自定义缓冲处理函数来进行读、写、清除缓冲文件。

Create a function in your application that Smarty will use as a cache handler. Set the name of it in the $cache_handler_func class variable. Smarty will now use this to handle cached data. The first argument is the action, which will be one of 'read', 'write' and 'clear'. The second parameter is the Smarty object. The third parameter is the cached content. Upon a write, Smarty passes the cached content in these parameters. Upon a 'read', Smarty expects your function to accept this parameter by reference and populate it with the cached data. Upon a 'clear', pass a dummy variable here since it is not used. The fourth parameter is the name of the template file (needed for read/write), the fifth parameter is the cache_id (optional), and the sixth is the compile_id (optional).

如果要在应用程序下建立一个函数，SMARTY将会使用一个缓冲处理。设置这个函数名为 $cache handler func 中类变量名。Smarty将使用这个函数来处理缓冲数据。第一个参数不管是‘读’，‘写’，‘清除’，都是动态的。第二个参数是 Smarty 对象。第三个参数是缓冲的内容。在进行写操作之前，Smarty 传递这些缓冲内容给这些参量。在进行读操作之前，Smarty预处理那些缓冲数据相关或者封装好了的函数。在进行清除操作之前，从他没有使用起，就传递一个虚拟变量。第四个参数是模板文件名（需要读和写的文件），第五个函数是缓冲ID（额外选项），然后第六个参数是编译的ID（额外选项）。

Note: The last parameter ($exp_time) was added in Smarty-2.6.0.

注意：最新的参数名 （$exp_time) 在Smarty-2.6.0中才加入的。

Example 15-5. example using MySQL as a cache source

<?php
/*

example usage:

include('Smarty.class.php');
include('mysql_cache_handler.php');

$smarty = new Smarty;
$smarty->cache_handler_func = 'mysql_cache_handler';

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

mysql database is expected in this format:

create database SMARTY_CACHE;

create table CACHE_PAGES(
CacheID char(32) PRIMARY KEY,
CacheContents MEDIUMTEXT NOT NULL
);

*/

function mysql_cache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null, $exp_time=null)
{
    // set db host, user and pass here
    $db_host = 'localhost';
    $db_user = 'myuser';
    $db_pass = 'mypass';
    $db_name = 'SMARTY_CACHE';
    $use_gzip = false;

    // create unique cache id
    $CacheID = md5($tpl_file.$cache_id.$compile_id);

    if(! $link = mysql_pconnect($db_host, $db_user, $db_pass)) {
        $smarty_obj->_trigger_error_msg("cache_handler: could not connect to database");
        return false;
    }
    mysql_select_db($db_name);

    switch ($action) {
        case 'read':
            // save cache to database
            $results = mysql_query("select CacheContents from CACHE_PAGES where CacheID='$CacheID'");
            if(!$results) {
                $smarty_obj->_trigger_error_msg("cache_handler: query failed.");
            }
            $row = mysql_fetch_array($results,MYSQL_ASSOC);

            if($use_gzip && function_exists("gzuncompress")) {
                $cache_contents = gzuncompress($row["CacheContents"]);
            } else {
                $cache_contents = $row["CacheContents"];
            }
            $return = $results;
            break;
        case 'write':
            // save cache to database

            if($use_gzip && function_exists("gzcompress")) {
                // compress the contents for storage efficiency
                $contents = gzcompress($cache_content);
            } else {
                $contents = $cache_content;
            }
            $results = mysql_query("replace into CACHE_PAGES values(
                            '$CacheID',
                            '".addslashes($contents)."')
                        ");
            if(!$results) {
                $smarty_obj->_trigger_error_msg("cache_handler: query failed.");
            }
            $return = $results;
            break;
        case 'clear':
            // clear cache info
            if(empty($cache_id) && empty($compile_id) && empty($tpl_file)) {
                // clear them all
                $results = mysql_query("delete from CACHE_PAGES");
            } else {
                $results = mysql_query("delete from CACHE_PAGES where CacheID='$CacheID'");
            }
            if(!$results) {
                $smarty_obj->_trigger_error_msg("cache_handler: query failed.");
            }
            $return = $results;
            break;
        default:
            // error, unknown action
            $smarty_obj->_trigger_error_msg("cache_handler: unknown action \"$action\"");
            $return = false;
            break;
    }
    mysql_close($link);
    return $return;

}

?>

Prev | Home | Next
Output Filters | Up | Resources


Resources

资源

Table of Contents
Templates from $template_dir
Templates from any directory
Templates from other sources
Default template handler function

The templates may come from a variety of sources. When you display or fetch a template, or when you include a template from within another template, you supply a resource type, followed by the appropriate path and template name. If a resource is not explicitly given the value of $default_resource_type is assumed.

模板可以来自各种各样的资源。当你显示或者取得一个模板，或者当你在一个模板里面包含另外一个模板时，只要提供一个类型的资源，紧跟正确的路径和模板名。如果一个模板资源没有明确的给出 $default resource type 变量值，就认为这个资源为假定值。

Prev | Home | Next
Cache Handler Function | Up | Templates from $template_dir


Templates from $template_dir

Templates from the $template_dir do not require a template resource, although you can use the file: resource for consistancy. Just supply the path to the template you want to use relative to the $template_dir root directory.

Example 15-6. using templates from $template_dir

// from PHP script
$smarty->display("index.tpl");
$smarty->display("admin/menu.tpl");
$smarty->display("file:admin/menu.tpl"); // same as one above

{* from within Smarty template *}
{include file="index.tpl"}
{include file="file:index.tpl"} {* same as one above *}

Prev | Home | Next
Resources | Up | Templates from any directory


Templates from any directory

Table of Contents
Windows Filepaths

Templates outside of the $template_dir require the file: template resource type, followed by the absolute path and name of the template.

Example 15-7. using templates from any directory

// from PHP script
$smarty->display("file:/export/templates/index.tpl");
$smarty->display("file:/path/to/my/templates/menu.tpl");

{* from within Smarty template *}
{include file="file:/usr/local/share/templates/navigation.tpl"}

Windows Filepaths

If you are using a Windows machine, filepaths usually include a drive letter (C:) at the beginning of the pathname. Be sure to use "file:" in the path to avoid namespace conflicts and get the desired results.

Example 15-8. using templates from windows file paths

// from PHP script
$smarty->display("file:C:/export/templates/index.tpl");
$smarty->display("file:F:/path/to/my/templates/menu.tpl");

{* from within Smarty template *}
{include file="file:D:/usr/local/share/templates/navigation.tpl"}

Prev | Home | Next
Templates from $template_dir | Up | Templates from other sources


Templates from other sources

You can retrieve templates using whatever possible source you can access with PHP: databases, sockets, LDAP, and so on. You do this by writing resource plugin functions and registering them with Smarty.

See resource plugins section for more information on the functions you are supposed to provide.

Note: Note that you cannot override the built-in file resource, but you can provide a resource that fetches templates from the file system in some other way by registering under another resource name.

Example 15-9. using custom resources

// from PHP script

// put these function somewhere in your application
function db_get_template ($tpl_name, &$tpl_source, &$smarty_obj)
{
 // do database call here to fetch your template,
 // populating $tpl_source
 $sql = new SQL;
 $sql->query("select tpl_source
 from my_table
 where tpl_name='$tpl_name'");
 if ($sql->num_rows) {
 $tpl_source = $sql->record['tpl_source'];
 return true;
 } else {
 return false;
 }
}

function db_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj)
{
 // do database call here to populate $tpl_timestamp.
 $sql = new SQL;
 $sql->query("select tpl_timestamp
 from my_table
 where tpl_name='$tpl_name'");
 if ($sql->num_rows) {
 $tpl_timestamp = $sql->record['tpl_timestamp'];
 return true;
 } else {
 return false;
 }
}

function db_get_secure($tpl_name, &$smarty_obj)
{
 // assume all templates are secure
 return true;
}

function db_get_trusted($tpl_name, &$smarty_obj)
{
 // not used for templates
}

// register the resource name "db"
$smarty->register_resource("db", array("db_get_template",
 "db_get_timestamp",
 "db_get_secure",
 "db_get_trusted"));

// using resource from php script
$smarty->display("db:index.tpl");

{* using resource from within Smarty template *}
{include file="db:/extras/navigation.tpl"}

Prev | Home | Next
Templates from any directory | Up | Default template handler function


Default template handler function

You can specify a function that is used to retrieve template contents in the event the template cannot be retrieved from its resource. One use of this is to create templates that do not exist on-the-fly.

Example 15-10. using the default template handler function

<?php
// put this function somewhere in your application

function make_template ($resource_type, $resource_name, &$template_source, &$template_timestamp, &$smarty_obj)
{
    if( $resource_type == 'file' ) {
        if ( ! is_readable ( $resource_name )) {
            // create the template file, return contents.
            $template_source = "This is a new template.";
            $template_timestamp = time();
            $smarty_obj->_write_file($resource_name,$template_source);
            return true;
        }
 } else {
        // not a file
        return false;
 }
}

// set the default handler
$smarty->default_template_handler_func = 'make_template';
?>

Prev | Home | Next
Templates from other sources | Up | Extending Smarty With Plugins


Extending Smarty With Plugins 以插件扩展Smarty

Prev Next

Chapter 16. Extending Smarty With Plugins
[第十六章.以插件扩展Smarty]

Table of Contents
How Plugins Work 插件如何工作
Naming Conventions 命名约定
Writing Plugins 编写插件
Template Functions 模板函数插件
Modifiers 修饰插件
Block Functions 区块函数插件
Compiler Functions 编译函数插件
Prefilters/Postfilters 预滤器/补滤器插件
Output Filters 输出过滤插件
Resources 资源插件
Inserts 嵌入插件

Version 2.0 introduced the plugin architecture that is used for almost all the customizable functionality of Smarty. This includes:

2.0版本引入了被广泛应用于自定义Smarty功能的插件机制。它包括如下类型：

  • functions 函数插件
  • modifiers 修饰插件
  • block functions 区块函数插件
  • compiler functions 编译函数插件
  • prefilters 预滤器插件
  • postfilters 补滤器插件
  • outputfilters 输出过滤插件
  • resources 资源插件
  • inserts 嵌入插件
With the exception of resources, backwards compatibility with the old way of registering handler functions via register_* API is preserved. If you did not use the API but instead modified the class variables $custom_funcs, $custom_mods, and other ones directly, then you will need to adjust your scripts to either use the API or convert your custom functionality into plugins.

为了与旧有方式保持向后兼容，除资源插件外，保留了通过register_* API方式装载函数的 处理方法。如果你不是使用API方式而是使用直接修改类变量 $custom_funcs, $custom_mods 等的方法，那么你就需要修改你的程序了。或者使用API的方法，或者将你的自定义功能转换成插件。

How Plugins Work
插件如何工作

Plugins are always loaded on demand. Only the specific modifiers, functions, resources, etc invoked in the templates scripts will be loaded. Moreover, each plugin is loaded only once, even if you have several different instances of Smarty running within the same request.

插件总在需要的时候被装载。只有在模板脚本里调用的特定修饰、函数、资源插件等会被装载。此外，即便在同一个请求中有几个不同的Smarty实体运行，每个插件也只被装载一次。

Pre/postfilters and output filters are a bit of a special case. Since they are not mentioned in the templates, they must be registered or loaded explicitly via API functions before the template is processed. The order in which multiple filters of the same type are executed depends on the order in which they are registered or loaded.

预/补过滤器插件和输出过滤器插件的装载方式有些不同。由于在模板中未被提及，它们必须在模板被处理前通过API函数明确地装入系统。同类型的多个过滤器插件依据被装载的次序先后不同分别先后执行。

The plugins directory can be a string containing a path or an array containing multiple paths. To install a plugin, simply place it in one of the directories and Smarty will use it automatically.

插件目录是包含一条路径信息的字符串或包含多条路径信息的字符串数组。安装插件的时候，将插件置于其中一个目录下，Smarty会自动识别使用。

Prev 上一页 | Home 回顶部 | Next 下一页
Default template handler function 缺省模板处理函数 | Up 向上 | Naming Conventions 命名约定


Naming Conventions 命名约定

Prev Chapter 16. Extending Smarty With Plugins Next

Naming Conventions
命名约定

Plugin files and functions must follow a very specific naming convention in order to be located by Smarty.

插件文件和函数必须遵循特定的命名约定以便Smarty识别。

The plugin files must be named as follows:

插件文件必须命名如下：

type . name .php

Where type is one of these plugin types:

其中type是如下插件中的一种：

  • function
  • modifier
  • block
  • compiler
  • prefilter
  • postfilter
  • outputfilter
  • resource
  • insert

And name should be a valid identifier (letters, numbers, and underscores only).

name为仅包含字母、数字和下划线的合法标志符。

Some examples例如: function.html_select_date.php, resource.db.php, modifier.spacify.php.

The plugin functions inside the plugin files must be named as follows:

插件内的函数应遵循如下命名约定：

smarty_ type _ name ()

The meanings of type and name are the same as before.

type和name的意义如前。

Smarty will output appropriate error messages if the plugin file it needs is not found, or if the file or the plugin function are named improperly.

如果指定的插件文件不存在或命名不合规范，Smarty会输出相应的错误信息。

Prev 上一页 | Home 回顶部 | Next 下一页
Extending Smarty With Plugins 以插件扩展Smarty | Up 向上 | Writing Plugins 编写插件


Writing Plugins 命名约定

Prev Chapter 16. Extending Smarty With Plugins Next

Writing Plugins
编写插件

Plugins can be either loaded by Smarty automatically from the filesystem or they can be registered at runtime via one of the register_* API functions. They can also be unregistered by using unregister_* API functions.

Smarty可自动从文件系统装载插件，或者运行时通过register_* API函数装载。 可以通过unregister_* API函数卸载已经装载的插件。

For the plugins that are registered at runtime, the name of the plugin function(s) does not have to follow the naming convention.

只在运行时装载的插件的函数名称不需要遵守命名约定。

If a plugin depends on some functionality provided by another plugin (as is the case with some plugins bundled with Smarty), then the proper way to load the needed plugin is this:

如果某个插件依赖其它插件内的某些功能（例如某些插件功能捆绑于Smarty内），那么可以通过如下方法装载必须的插件：

require_once $smarty->_get_plugin_filepath('function', 'html_options');

As a general rule, Smarty object is always passed to the plugins as the last parameter (with two exceptions: modifiers do not get passed the Smarty object at all and blocks get passed &$repeat after the Smarty object to keep backwards compatibility to older versions of Smarty).

Smarty对象通常作为传递给插件的最后一个参数（有两个例外：1、修饰插件根本不接受传递过来的Smarty对象。2、为了向上兼容老版本的Smarty，区块插件将 &$repeat 作为最后一个参数，因此Smarty对象是倒数第二个参数。）

Prev 上一页 | Home 回顶部 | Next 下一页
Naming Conventions 命名约定 | Up 向上 | Template Functions 模板函数


Template Functions

Prev Chapter 16. Extending Smarty With Plugins Next

Template Functions
模板函数

void smarty_function_ name (array $params, object &$smarty)

All attributes passed to template functions from the template are contained in the $params as an associative array. Either access those values directly, e.g. $params['start'] or use extract($params) to import them into the symbol table.

模板传递给模板函数的所有的属性都包含在参数数组 $params 中，既可以通过如： $params['start'] 的方式直接处理其中的值，也可以使用 extract($params) 的方式将所有值导入符号表中。

The output (return value) of the function will be substituted in place of the function tag in the template (fetch() function, for example). Alternatively, the function can simply perform some other task without any output (assign() function).

函数输出（返回值）的内容将取代模板中函数名称出现的位置（例如：fetch()函数）。同时函数也可能只是执行些后台任务，并无任何输出

If the function needs to assign some variables to the template or use some other Smarty-provided functionality, it can use the supplied $smarty object to do so.

如果函数需要向模板中增加变量或者使用Smarty提供的某些功能，可以通过 $smarty 对象实现。

See also相关内容: register_function(), unregister_function().

Example 16-1. function plugin with output
例16-1：有输出插件函数

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File: function.eightball.php
 * Type: function
 * Name: eightball
 * Purpose: outputs a random magic answer
 * -------------------------------------------------------------
 */
function smarty_function_eightball($params, &$smarty)
{
 $answers = array('Yes',
 'No',
 'No way',
 'Outlook not so good',
 'Ask again soon',
 'Maybe in your reality');

 $result = array_rand($answers);
 return $answers[$result];
}
?>

which can be used in the template as:

在模板中调用方法如下：

Question: Will we ever have time travel?
Answer: {eightball}.

Example 16-2. function plugin without output
例16-2：无输出插件函数

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File: function.assign.php
 * Type: function
 * Name: assign
 * Purpose: assign a value to a template variable
 * -------------------------------------------------------------
 */
function smarty_function_assign($params, &$smarty)
{
 extract($params);

 if (empty($var)) {
 $smarty->trigger_error("assign: missing 'var' parameter");
 return;
 }

 if (!in_array('value', array_keys($params))) {
 $smarty->trigger_error("assign: missing 'value' parameter");
 return;
 }

 $smarty->assign($var, $value);
}
?>

Prev 上一页 | Home 回顶部 | Next 下一页
Writing Plugins 编写插件 | Up 向上 | Modifiers 修饰插件


Modifiers

Prev Chapter 16. Extending Smarty With Plugins
利用插件扩展Smarty 		Next

Modifiers修正器

Modifiers are little functions that are applied to a variable in the template before it is displayed or used in some other context. Modifiers can be chained together.
修正器是一些短小的函数，这些函数被应用于模版中的一个变量，然后变量再显示或用于其他的一些文档。我们可以把修正器链接起来。

mixed smarty_modifier_ name (mixed $value, [mixed $param1, ...])

The first parameter to the modifier plugin is the value on which the modifier is supposed to operate. The rest of the parameters can be optional, depending on what kind of operation is supposed to be performed.
修正器插件的第一个参数是不可缺少的。剩余的参数是可选的，它们的有无取决于期望执行哪一种操作。

The modifier has to return the result of its processing.
修正器必须有返回值。

See also register_modifier(), unregister_modifier().
也可参考register_modifier(), unregister_modifier().

Example 16-3. simple modifier plugin简单修正器插件

This plugin basically aliases one of the built-in PHP functions. It does not have any additional parameters.
这个插件主要目的是用另一个名字替换一个内置PHP函数的名字。他没有任何多余的参数。

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File: modifier.capitalize.php
 * Type: modifier
 * Name: capitalize
 * Purpose: capitalize words in the string
 * -------------------------------------------------------------
 */
function smarty_modifier_capitalize($string)
{
 return ucwords($string);
}
?>

Example 16-4. more complex modifier plugin更加复杂的修正器插件

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File: modifier.truncate.php
 * Type: modifier
 * Name: truncate
 * Purpose: Truncate a string to a certain length if necessary,
 * optionally splitting in the middle of a word, and
 * appending the $etc string.
 * -------------------------------------------------------------
 */
function smarty_modifier_truncate($string, $length = 80, $etc = '...',
 $break_words = false)
{
 if ($length == 0)
 return '';

 if (strlen($string) > $length) {
 $length -= strlen($etc);
 $fragment = substr($string, 0, $length+1);
 if ($break_words)
 $fragment = substr($fragment, 0, -1);
 else
 $fragment = preg_replace('/\s+(\S+)?$/', '', $fragment);
 return $fragment.$etc;
 } else
 return $string;
}
?>

Prev | Home | Next
Template Functions[模板函数] | Up | [块函数]Block Functions


Block Functions

Prev Chapter 16. Extending Smarty With Plugins
利用插件扩展Smarty 		Next

Block Functions块函数

void smarty_block_ name (array $params, mixed $content, object &$smarty)

Block functions are functions of the form: {func} .. {/func}. In other words, they enclose a template block and operate on the contents of this block. Block functions take precedence over custom functions of the same name, that is, you cannot have both custom function {func} and block function {func} .. {/func}.
块函数的形式是这样的：{func} .. {/func}。换句话说，他们用标记圈起一个块，然后对这个块的内容进行操作。块函数优先于同名的传统函数，即你不能同时有通明的传统函数{func}和块函数{func} .. {/func}。

By default your function implementation is called twice by Smarty: once for the opening tag, and once for the closing tag (see &$repeat below how to change this).
默认地你的函数执行被Smarty调用两次：一次是在开始标记，另一次是在结束标记（参考下面的&$repeat怎样改变这种情况）

Only the opening tag of the block function may have attributes. All attributes passed to template functions from the template are contained in the $params as an associative array. You can either access those values directly, e.g. $params['start'] or use extract($params) to import them into the symbol table. The opening tag attributes are also accessible to your function when processing the closing tag.
块函数仅开始标记可以有属性。所有从模板传替给模板函数的属性被囊括与一个集合数组参数中。你可以直接获取其值，例如：$params['start']或者是用extract($params)将它们导入符号表中。当处理结束标记时，开始标记的属性对你的函数也是可用的。

The value of $content variable depends on whether your function is called for the opening or closing tag. In case of the opening tag, it will be null, and in case of the closing tag it will be the contents of the template block. Note that the template block will have already been processed by Smarty, so all you will receive is the template output, not the template source.
变量 $content 的值取决于是否因开始标记或结束标记调用你的函数。假如是开始标记，它会是空的，如果是结束标记，它会是模板块的内容。请注意模板块已经被Smarty处理,所以你接收到的结果是输出后的模板而不是原样模板。

The parameter &$repeat is passed by reference to the function implementation and provides a possibility for it to control how many times the block is displayed. By default $repeat is true at the first call of the block-function (the block opening tag) and false on all subsequent calls to the block function (the block's closing tag). Each time the function implementation returns with &$repeat being true, the contents between {func} .. {/func} are evaluated and the function implementation is called again with the new block contents in the parameter $content .
参数 &$repeat 通过参考引用传递给函数执行过程并为其提供一个可能值来控制显示块多少遍。默认情况下在首次调用块函数（块开始标记）时变量 $repeat 是真，在随后的所有块函数调用中其始终是假。每当函数执行返回的 &$repeat 是真时，在{func} .. {/func}之间的内容再次求值,函数执行接收一个新块参数 $content 内容值被再次调用。

If you have nested block functions, it's possible to find out what the parent block function is by accessing $smarty->_tag_stack variable. Just do a var_dump() on it and the structure should be apparent.
如果你嵌套了块函数，通过访问变量$smarty->_tag_stack 找出父块函数是可能的。仅仅对块函数运行一下var_dump()，函数结构就会一目了然了。

See also: register_block(), unregister_block().

Example 16-5. block function

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File: block.translate.php
 * Type: block
 * Name: translate
 * Purpose: translate a block of text
 * -------------------------------------------------------------
 */
function smarty_block_translate($params, $content, &$smarty)
{
 if (isset($content)) {
 $lang = $params['lang'];
 // do some intelligent translation thing here with $content
 return $translation;
 }
}

Prev | Home | Next
Modifiers[修正器] | Up | [编译函数]Compiler Functions


Compiler Functions

Prev Chapter 16. Extending Smarty With Plugins
利用插件扩展smarty 		Next

Compiler Functions编译函数

Compiler functions are called only during compilation of the template. They are useful for injecting PHP code or time-sensitive static content into the template. If there is both a compiler function and a custom function registered under the same name, the compiler function has precedence.
编译函数仅在模板编译过程中被调用。对于将PHP代码或对时间敏感的静态内容嵌入到模板中，他们是比较有用的。如果编译函数和普通函数都注册了同一个名字，则编译函数具有优先使用权。

mixed smarty_compiler_ name (string $tag_arg, object &$smarty)

The compiler function is passed two parameters: the tag argument string - basically, everything from the function name until the ending delimiter, and the Smarty object. It's supposed to return the PHP code to be injected into the compiled template.
此编译函数有两个参数：标记参数字符串——基本上是从函数名字直到结束位置的所有内容，另一个参数是Smarty对象。该函数将返回嵌入到被编译模板中的PHP代码。

See also register_compiler_function(), unregister_compiler_function().

Example 16-6. simple compiler function简单编译函数

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File: compiler.tplheader.php
 * Type: compiler
 * Name: tplheader
 * Purpose: Output header containing the source file name and
 * the time it was compiled.
 * -------------------------------------------------------------
 */
function smarty_compiler_tplheader($tag_arg, &$smarty)
{
 return "\necho '" . $smarty->_current_file . " compiled at " . date('Y-m-d H:M'). "';";
}
?>

This function can be called from the template as:
这个函数在模板中以如下方式调用：

{* this function gets executed at compile time only *}
{tplheader}

The resulting PHP code in the compiled template would be something like this:
在编译之后的模板中被嵌入的PHP代码内容如下：

<php
echo 'index.tpl compiled at 2002-02-20 20:02';
?>

Prev | Home | Next
Block Functions[块函数] | Up | [预滤器/后滤器]Prefilters/Postfilters


Prefilters/Postfilters

Prev Chapter 16. Extending Smarty With Plugins
利用插件扩展smarty 		Next

Prefilters/Postfilters预滤器/后滤器

Prefilter and postfilter plugins are very similar in concept; where they differ is in the execution -- more precisely the time of their execution.
从概念上看，预滤器和后滤器插件都很简单；不同之处就在于它们的执行，更确切地说是它们的执行时刻（非时间段，而是某一个时刻）。

string smarty_prefilter_ name (string $source, object &$smarty)

Prefilters are used to process the source of the template immediately before compilation. The first parameter to the prefilter function is the template source, possibly modified by some other prefilters. The plugin is supposed to return the modified source. Note that this source is not saved anywhere, it is only used for compilation.
预滤器用来在编译之前直接处理模板源文件。预滤器函数的第一个参数是模板源文件，该文件可能被其他一些预滤器修正过。此预滤器插件将返回修正过的源文件。请记住此源文件仅用来编译，它不会在任何地方被保存。

string smarty_postfilter_ name (string $compiled, object &$smarty)

Postfilters are used to process the compiled output of the template (the PHP code) immediately after the compilation is done but before the compiled template is saved to the filesystem. The first parameter to the postfilter function is the compiled template code, possibly modified by other postfilters. The plugin is supposed to return the modified version of this code.
后滤器用来在编译之后直接处理模板的编译输出（PHP代码），但须在编译之后的模板被保存到文件系统之前就进行操作。预滤器函数的第一个参数是编译之后的模板代码，该代码可能被其他一些后滤器修正过。此后滤器插件将返回修正过的代码文件。

Example 16-7. prefilter plugin预滤器插件

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File: prefilter.pre01.php
 * Type: prefilter
 * Name: pre01
 * Purpose: Convert html tags to be lowercase.
 * -------------------------------------------------------------
 */
 function smarty_prefilter_pre01($source, &$smarty)
 {
 return preg_replace('!<(\w+)[^>]+>!e', 'strtolower("$1")', $source);
 }
?>

Example 16-8. postfilter plugin后滤器插件

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File: postfilter.post01.php
 * Type: postfilter
 * Name: post01
 * Purpose: Output code that lists all current template vars.
 * -------------------------------------------------------------
 */
 function smarty_postfilter_post01($compiled, &$smarty)
 {
 $compiled = "<pre>\n<?php print_r(\$this->get_template_vars()); ?>\n</pre>" . $compiled;
 return $compiled;
 }
?>

Prev | Home | Next
Compiler Functions[编译函数] | Up | [输出过滤器]Output Filters


Output Filters

Prev Chapter 16. Extending Smarty With Plugins
利用插件扩展smarty 		Next

Output Filters输出过滤器

Output filter plugins operate on a template's output, after the template is loaded and executed, but before the output is displayed.
输出过滤器插件的作用是，在装载并执行完一个模板之后显示模板之前，操作该模板的输出。

string smarty_outputfilter_ name (string $template_output, object &$smarty)

The first parameter to the output filter function is the template output that needs to be processed, and the second parameter is the instance of Smarty invoking the plugin. The plugin is supposed to do the processing and return the results.
输出过滤器函数第一个参数是需要处理的模板输出，第二个参数是调用这个插件的Smarty实例。此插件将会对参数进行处理并返回相应的结果。

Example 16-9. output filter plugin输出过滤器插件

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File: outputfilter.protect_email.php
 * Type: outputfilter
 * Name: protect_email
 * Purpose: Converts @ sign in email addresses to %40 as
 * a simple protection against spambots
 * -------------------------------------------------------------
 */
 function smarty_outputfilter_protect_email($output, &$smarty)
 {
 return preg_replace('!(\S+)@([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,3}|[0-9]{1,3}))!',
 '$1%40$2', $output);
 }

Prev | Home | Next
Prefilters/Postfilters[预滤器/后滤器] | Up | [源]Resources


Resources

Prev Chapter 16. Extending Smarty With Plugins
利用插件扩展smarty 		Next

Resources资源

Resource plugins are meant as a generic way of providing template sources or PHP script components to Smarty. Some examples of resources: databases, LDAP, shared memory, sockets, and so on.
资源插件被认为是为Smarty提供模板源或PHP脚本组件的一种普通方式。一些资源例子如:数据库、LDAP、共享内存、sockets（套接字）等等。

There are a total of 4 functions that need to be registered for each type of resource. Every function will receive the requested resource as the first parameter and the Smarty object as the last parameter. The rest of parameters depend on the function.
需要为每一种类型的资源注册四个函数。每一个函数将接收被请求的资源作为第一个参数，Smarty对象作为最后一个参数。剩余的参数取决于函数的不同。

bool smarty_resource_ name _source (string $rsrc_name, string &$source, object &$smarty)

bool smarty_resource_ name _timestamp (string $rsrc_name, int &$timestamp, object &$smarty)

bool smarty_resource_ name _secure (string $rsrc_name, object &$smarty)

bool smarty_resource_ name _trusted (string $rsrc_name, object &$smarty)

The first function is supposed to retrieve the resource. Its second parameter is a variable passed by reference where the result should be stored. The function is supposed to return true if it was able to successfully retrieve the resource and false otherwise.
第一个函数将会检索资源。它的第二个参数是一个参考引用变量，结果值会存放到该变量里面。如果此函数能成功的检索到资源，将会返回true，否则返回false。

The second function is supposed to retrieve the last modification time of the requested resource (as a UNIX timestamp). The second parameter is a variable passed by reference where the timestamp should be stored. The function is supposed to return true if the timestamp could be succesfully determined, and false otherwise.
第二个函数将会检索被请求资源的最后修改时间（UNIX时间戳）。它的第二个参数是一个参考引用变量，时间戳值会存放到该变量里面。如果此函数能成功的确定时间戳，将会返回true，否则返回false。

The third function is supposed to return true or false, depending on whether the requested resource is secure or not. This function is used only for template resources but should still be defined.
第三个函数将会返回true或false，取决于被请求资源是否安全。这个函数仅用于模板资源，但仍应被定义。

The fourth function is supposed to return true or false, depending on whether the requested resource is trusted or not. This function is used for only for PHP script components requested by {include_php} tag or {insert} tag with src attribute. However, it should still be defined even for template resources.
第四个函数将会返回true或false，取决于被请求资源是否被信任。这个函数仅用于被 {include_php} 或 {insert} 标记以 src 属性请求的PHP脚本组件。但仍应被定义，甚至用于模板资源也不例外。

See also register_resource(), unregister_resource().

Example 16-10. resource plugin资源插件

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File: resource.db.php
 * Type: resource
 * Name: db
 * Purpose: Fetches templates from a database
 * -------------------------------------------------------------
 */
function smarty_resource_db_source($tpl_name, &$tpl_source, &$smarty)
{
 // do database call here to fetch your template,
 // populating $tpl_source
 $sql = new SQL;
 $sql->query("select tpl_source
 from my_table
 where tpl_name='$tpl_name'");
 if ($sql->num_rows) {
 $tpl_source = $sql->record['tpl_source'];
 return true;
 } else {
 return false;
 }
}

function smarty_resource_db_timestamp($tpl_name, &$tpl_timestamp, &$smarty)
{
 // do database call here to populate $tpl_timestamp.
 $sql = new SQL;
 $sql->query("select tpl_timestamp
 from my_table
 where tpl_name='$tpl_name'");
 if ($sql->num_rows) {
 $tpl_timestamp = $sql->record['tpl_timestamp'];
 return true;
 } else {
 return false;
 }
}

function smarty_resource_db_secure($tpl_name, &$smarty)
{
 // assume all templates are secure
 return true;
}

function smarty_resource_db_trusted($tpl_name, &$smarty)
{
 // not used for templates
}
?>

Prev | Home | Next
Output Filters[输出过滤器] | Up | [插入]Inserts


Inserts

Prev Chapter 16. Extending Smarty With Plugins
利用插件扩展smarty 		Next

Inserts插入

Insert plugins are used to implement functions that are invoked by {insert} tags in the template.
插入插件用来执行在模板中被 {insert} 标记调用的函数 。

string smarty_insert_ name (array $params, object &$smarty)

The first parameter to the function is an associative array of attributes passed to the insert. Either access those values directly, e.g. $params['start'] or use extract($params) to import them into the symbol table.
函数的第一个参数是一个传递给插入动作的属性集合数组。每一种方式都可以直接获取那些属性值，例如$params['start']，或用extract($params)将属性导入符号表中。

The insert function is supposed to return the result which will be substituted in place of the {insert} tag in the template.
插入函数将会返回某值，该值将在模板中的 {insert} 标记处被替换。

Example 16-11. insert plugin插入插件

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File: insert.time.php
 * Type: time
 * Name: time
 * Purpose: Inserts current date/time according to format
 * -------------------------------------------------------------
 */
function smarty_insert_time($params, &$smarty)
{
 if (empty($params['format'])) {
 $smarty->trigger_error("insert time: missing 'format' parameter");
 return;
 }

 $datetime = strftime($params['format']);
 return $datetime;
}
?>

Prev | Home | Next
Resources[资源] | Up | [附属]Appendixes


Troubleshooting

Prev Next

Chapter 17. Troubleshooting疑难解答

Table of Contents
Smarty/PHP errors错误

Smarty/PHP errors错误

Smarty can catch many errors such as missing tag attributes or malformed variable names. If this happens, you will see an error similar to the following:

Smarty能够发现许多类似缺少标签属性或者不规范变量名这样的错误。如果发生这种错误，就会有下面的错误提示：

Example 17-1. Smarty errors错误

Warning: Smarty: [in index.tpl line 4]: syntax error: unknown tag - '%blah'
 in /path/to/smarty/Smarty.class.php on line 1041
警告：Smarty: 在index.tpl文件第4行，语法错误:'%blah'标签未知

Fatal error: Smarty: [in index.tpl line 28]: syntax error: missing section name
 in /path/to/smarty/Smarty.class.php on line 1041
严重错误：Smarty: 在index.tpl文件第28行，语法错误:缺少节段名字在 /path/to/smarty/路径中的Smarty.class.php文件1041行

Smarty shows you the template name, the line number and the error. After that, the error consists of the actual line number in the Smarty class that the error occured.

Smarty可以显示模板名称以及行号和错误。这些错误显示未所发生错误所属的smarty类所在的实际行号。

There are certain errors that Smarty cannot catch, such as missing close tags. These types of errors usually end up in PHP compile-time parsing errors.

某些错误Smarty不能捕捉，像缺少结束标签。这些类型的错误通常会在在php分析语法错误的编译时间中就捕捉出来了.

Example 17-2. PHP parsing errors

Parse error: parse error in /path/to/smarty/templates_c/index.tpl.php on line 75

When you encounter a PHP parsing error, the error line number will correspond to the compiled PHP script, not the template itself. Usually you can look at the template and spot the syntax error. Here are some common things to look for: missing close tags for {if}{/if} or {section}{/section}, or syntax of logic within an {if} tag. If you can't find the error, you might have to open the compiled PHP file and go to the line number to figure out where the corresponding error is in the template.

当你遇到一个php解析错误时，错误行号将反应到php编译脚本，而不是模板本身。通常，你会看到模板并发现语法错误。通常会发现：缺少if}{/if} 或者
 {section}{/section}的结束标签。或者{if}标签内的逻辑语法错误。如果你不能检查出错误，那就得在模板中打开php编译文件按照行号找出相应错误。
Prev Home Next
Appendixes
附录
 Up
Tips & Tricks
使用技巧和经验


Tips & Tricks

Prev Next

Chapter 18. Tips & Tricks

第18章。使用技巧和经验

Table of Contents
[内容列表]
Blank Variable Handling[空白变量处理]
Default Variable Handling[默认变量处理]
Passing variable title to header template[把变量型标题传递到头模板]
Dates[日期]
WAP/WML[WAP/WML]
Componentized Templates[组合的模板]
Obfuscating E-mail Addresses[拒绝电子邮件地址]

Blank Variable Handling

空白变量处理

There may be times when you want to print a default value for an empty variable instead of printing nothing, such as printing "&nbsp;" so that table backgrounds work properly. Many would use an {if} statement to handle this, but there is a shorthand way with Smarty, using the default variable modifier.

也许有时候你想给一个没有赋值的变量输出一个默认的值来代替什么也不输出，比如输出'&nbsp;'[这是一个空格符号，HTML里的标记]来使得表格里的背景能够正常工作。大多数人使用{if}语句来处理这些，但是用Smatry这里有一个捷径，那就是使用 default [默认的]值赋给变量。

Example 18-1. Printing &nbsp; when a variable is empty

例 18-1。输出&nbsp;---如果一个变量是空值

{* the long way *}

{if $title eq ""}
    &nbsp;
{else}
    {$title}
{/if}

{* the short way *}

{$title|default:"&nbsp;"}

Prev | Home | Next
Troubleshooting [疑难解答] | Up | Default Variable Handling [默认变量处理]


Default Variable Handling

默认变量处理

If a variable is used frequently throughout your templates, applying the default modifier every time it is mentioned can get a bit ugly. You can remedy this by assigning the variable its default value with the assign function.

如果一个变量在你的整个模板里被经常使用，而当你每次要用到这个变量的时候就给它赋默认的值，那将是无法忍受的。你可以通过使用 assign[赋值]这个函数来给这个变量赋上它的默认值来你补救。

Example 18-2. Assigning a template variable its default value

例 18-2.赋给一个模板变量默认的值

{* do this somewhere at the top of your template *}
{assign var="title" value=$title|default:"no title"}

{* if $title was empty, it now contains the value "no title" when you print it *}
{$title}

Prev | Home | Next
Tips & Tricks [使用技巧和经验] | Up | Passing variable title to header template [传递变量标题给头模板]


Passing variable title to header template

传递变量标题给头模板

When the majority of your templates use the same headers and footers, it is common to split those out into their own templates and include them. But what if the header needs to have a different title, depending on what page you are coming from? You can pass the title to the header when it is included.

当你的大多数模板文件用到了一些相同的头模板文件和脚模板文件，通常是把这些模板分开并且包含他们。但是如果头模板需要什么来使得显示一些不同的标题，取决于你用到的那些页面？你可以传递这些标题给头模板---当它们被包含的时候。

Example 18-3. Passing the title variable to the header template

例 18-3.传递变量标题给头模板

mainpage.tpl
------------

{include file="header.tpl" title="Main Page"}
{* template body goes here *}
{include file="footer.tpl"}

archives.tpl
------------

{config_load file="archive_page.conf"}
{include file="header.tpl" title=#archivePageTitle#}
{* template body goes here *}
{include file="footer.tpl"}

header.tpl
----------
<HTML>
<HEAD>
<TITLE>{$title|default:"BC News"}</TITLE>
</HEAD>
<BODY>

footer.tpl
----------
</BODY>
</HTML>

When the main page is drawn, the title of "Main Page" is passed to the header.tpl, and will subsequently be used as the title. When the archives page is drawn, the title will be "Archives". Notice in the archive example, we are using a variable from the archives_page.conf file instead of a hard coded variable. Also notice that "BC News" is printed if the $title variable is not set, using the default variable modifier.

当这个主页[main page]被浏览的时候，‘Main Page'这个标题就会传递给头模板文件[header.tpl]，并且结果会被用成为标题。当这个档案页[archives page]被浏览的时候，文件标题将会是‘Archives'。注意在这个档案页例子中，我们用了一个来自这个文件[archives_page.conf]的变量来代替一个硬性的代码变量。当然，要是变量[$title]没有初始化，我们会发现‘BC News'被输出----用那种使用默认值的变量的方法。

Prev | Home | Next
Default Variable Handling [默认变量处理] | Up | Dates [日期]


Dates

日期

As a rule of thumb, always pass dates to Smarty as timestamps. This allows template designers to use date_format for full control over date formatting, and also makes it easy to compare dates if necessary.

就像一条经验法则，经常是把日期当成时间戳传递给Smarty。 这样使得模板设计人员可以使用date_format[日期格式化]这个函数来对日期格式化进行全面控制，当然，这使得在需要比较日期的时候比较容易。

NOTE: As of Smarty 1.4.0, you can pass dates to Smarty as unix timestamps, mysql timestamps, or any date parsable by strtotime().

注意：从Smarty 1.4.0起，你可以像用unix中的时间戳,mysql中的时间戳,或者任何能够用这个函数[strtotime()]进行分析的时间戳那样把日期传递给Smarty。

Example 18-4. using date_format

例 18-4. 使用日期格式化

{$startDate|date_format}

OUTPUT:

Jan 4, 2001

{$startDate|date_format:"%Y/%m/%d"}

OUTPUT:

2001/01/04

{if $date1 < $date2}
    ...
{/if}

When using {html_select_date} in a template, The programmer will most likely want to convert the output from the form back into timestamp format. Here is a function to help you with that.

当在一个模板文件里使用{html_select_date}的时候，程序员将可能想在一个输出文件中把这种形式转回成时间戳的形式。下面就是一个可以帮助你达到目的的函数。

Example 18-5. converting form date elements back to a timestamp

// this assumes your form elements are named
// startDate_Day, startDate_Month, startDate_Year

$startDate = makeTimeStamp($startDate_Year,$startDate_Month,$startDate_Day);

function makeTimeStamp($year="",$month="",$day="")
{
    if(empty($year))
        $year = strftime("%Y");
    if(empty($month))
        $month = strftime("%m");
    if(empty($day))
        $day = strftime("%d");

    return mktime(0,0,0,$month,$day,$year);
}

Prev | Home | Next
Passing variable title to header template [传递变量标题给头模板] | Up | WAP/WML [WAP/WML]


WAP/WML

WAP/WML templates require a php Content-Type header to be passed along with the template. The easist way to do this would be to write a custom function that prints the header. If you are using caching, that won't work so we'll do it using the insert tag (remember insert tags are not cached!) Be sure that there is nothing output to the browser before the template, or else the header may fail.

WAP/WML模板需要一个说明文件内容形式的文件头和模板同时传递出去。最容易的方式就是编写一个客户型的函数用来输出这个文件头。如果你使用缓冲，那将不会起作用，所以我们使用一些插入标记（记住：插入标记不是缓冲！）。请确保在你的模板输出到浏览器之前没有任何东西被输出，否则文件头将实效。

Example 18-6. using insert to write a WML Content-Type header

例 18-6. 使用插入来写一个WML类型的文件头

// be sure apache is configure for the .wml extensions!
// put this function somewhere in your application, or in Smarty.addons.php
function insert_header() {
 // this function expects $content argument
 extract(func_get_arg(0));
 if(empty($content))
 return;
 header($content);
 return;
}

// your Smarty template _must_ begin with the insert tag example:

{insert name=header content="Content-Type: text/vnd.wap.wml"}

<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">

<!-- begin new wml deck -->
<wml>
<!-- begin first card -->
<card>
<do type="accept">
<go href="#two"/>
</do>
<p>
Welcome to WAP with Smarty!
Press OK to continue...
</p>
</card>
<!-- begin second card -->
<card id="two">
<p>
Pretty easy isn't it?
</p>
</card>
</wml>

Prev | Home | Next
Dates [日期] | Up | Componentized Templates [组合的模板]


Componentized Templates

组合的模板

This tip is a bit of a hack, but still a neat idea. Use at your own risk. ;-)

这项技巧有点普通，但是仍然是个不错的思想，如果要使用的话，自担风险。;-)

Traditionally, programming templates into your applications goes as follows: First, you accumulate your variables within your PHP application, (maybe with database queries.) Then, you instantiate your Smarty object, assign the variables and display the template. So lets say for example we have a stock ticker on our template. We would collect the stock data in our application, then assign these variables in the template and display it. Now wouldn't it be nice if you could add this stock ticker to any application by merely including the template, and not worry about fetching the data up front?

传统上，把模板编入你的应用程序中步骤如下：首先，你累计一下你的PHP程序中的变量，（可能用到数据库查询。）然后，你实例化一个你的Smarty对象，给变量赋值并且输出这个模板。因此，例如我们说我们在我们的模板里有一个资源标记。我们可以在我们的应用程序中收集这些资源数据，然后给模板中的这些变量赋值并输出。现在如果你仅仅是通过包含这些模板就可以把资源标记加入到任何一个应用程序中不是很好吗？

You can embed PHP into your templates with the {php}{/php} tags. With this, you can setup self contained templates with their own data structures for assigning their own variables. With the logic embedded like this, you can keep the template & logic together. This way no matter where the template source is coming from, it is always together as one component.

你可以通过使用{php}{/php}这两个标签来在你的模板里嵌入PHP。这样，你就能够建立包含自身的使用自己的数据结构的模板来给他们自身的变量赋值。通过像这样逻辑的嵌入，你能够把模板和逻辑性结合起来。这种方法使得模板不管源于何处总是像一个构件一样组合在一起。

Example 18-7. componentized template

例 18-7. 组合的模板

{* Smarty *}

{php}

    // setup our function for fetching stock data
    function fetch_ticker($symbol,&$ticker_name,&$ticker_price) {
        // put logic here that fetches $ticker_name
        // and $ticker_price from some resource
    }

    // call the function
    fetch_ticker("YHOO",$ticker_name,$ticker_price);

    // assign template variables
 $this->assign("ticker_name",$ticker_name);
 $this->assign("ticker_price",$ticker_price);

{/php}

Stock Name: {$ticker_name} Stock Price: {$ticker_price}

As of Smarty 1.5.0, there is even a cleaner way. You can include php in your templates with the {include_php ...} tag. This way you can keep your PHP logic separated from the template logic. See the include_php function for more information.

就像Smarty 1.5.0，这里有一种更清晰的方法。你可以在你的模板里使用{include_php ...}这些标签来包含php。使用这种方法，你能够保持PHP的逻辑性和模板的逻辑性分离。参照include_php 这个函数来获得更多信息。

Example 18-8. componentized template with include_php

例 18-8. 使用include_php组合的模板

load_ticker.php
---------------

<?php
    // setup our function for fetching stock data
    function fetch_ticker($symbol,&$ticker_name,&$ticker_price) {
        // put logic here that fetches $ticker_name
        // and $ticker_price from some resource
    }

    // call the function
    fetch_ticker("YHOO",$ticker_name,$ticker_price);

    // assign template variables
 $this->assign("ticker_name",$ticker_name);
 $this->assign("ticker_price",$ticker_price);
?>

index.tpl
---------

{* Smarty *}

{include_php file="load_ticker.php"}

Stock Name: {$ticker_name} Stock Price: {$ticker_price}

Prev | Home | Next
WAP/WML [WAP/WML] | Up | Obfuscating E-mail Addresses [拒绝电子邮件地址]


Obfuscating E-mail Addresses

拒绝电子邮件地址

Do you ever wonder how your E-mail address gets on so many spam mailing lists? One way spammers collect E-mail addresses is from web pages. To help combat this problem, you can make your E-mail address show up in scrambled javascript in the HTML source, yet it it will look and work correctly in the browser. This is done with the mailto plugin.

你想知道你的电子邮件地址是怎样出现在如此众多的猎头邮件列表中吗？猎头们收集电子邮件地址的一种方式就是从网页上获取。为了对抗这种方式，你可以让你的电子邮件在HTML源文件中以动态javascript的方式显示，这样在浏览器里就能正确的显示出来。这个是通过maito插件做到的。

Example 18-9. Example of Obfuscating an E-mail Address

例 18-9. 拒绝电子邮件地址的一个例子

index.tpl
---------

Send inquiries to
{mailto address=$EmailAddress encode="javascript" subject="Hello"}

Technical Note: This method isn't 100% foolproof. A spammer could conceivably program his e-mail collector to decode these values, but not likely.

技术提示：这种方法不是100%安全的。一个猎头可能知道编写他的电子邮件收集器来解码，但不是很可能的。

Prev | Home | Next
Componentized Templates [组合的模板] | Up | Resources [资源]


Resources

Prev Next

Chapter 19. Resources
第十九章. 相关资源

Smarty's homepage is located at http://smarty.php.net/. You can join the mailing list by sending an e-mail to smarty-general-subscribe@lists.php.net. An archive of the mailing list can be viewed at http://marc.theaimsgroup.com/?l=smarty&r=1&w=2
Smarty的主页位于http://smarty.php.net/。
您能加入邮件列表，通过发送邮件至信箱 smarty-general-subscribe@lists.php.net。您也可以通过如下链接加入邮件列表http://marc.theaimsgroup.com/?l=smarty&r=1&w=2

中文读者如果有任何关于Smarty的疑问或见解，可通过喜悦国际村与参与本手册翻译的相关村民直接讨论。

Prev | Home | Next
Obfuscating E-mail Addresses 拒绝电子邮件地址 | Up | BUGS 漏洞


BUGS

Prev

Chapter 20. BUGS
第二十章. 漏洞

Check the BUGS file that comes with the latest distribution of Smarty, or check the website.
最新的Smarty分卷可查阅漏洞文件，或上网查阅。（跟没说一样^^）
Smarty字符截取函数中文化、缓冲加速、模板技巧等，亦可通过喜悦国际村获得。

Prev | Home
Resources | Up


BUGS

Prev

Chapter 21. LIST
第二十一章. 翻译人员列表

本次义务翻译工作，为本村（喜悦国际村）村民自发组织，不代表任何人的意见和观点，如有不妥之处，望高人多来本村开坛讲经。

参与本次义务翻译工作的村民如下（排名不分先后）：

逃之夭夭 　　　　zhangyx@12365.sd.cn
kolin（老蒋）　　webmaster@im22.uni.cc
libk 　　　　　　libkhorse@sohu.com
huix　　　　　　 huix22@hotmail.com
flyhan　　　　　 hanbd7@sina.com
bralf　　　　　 ab_blunt@yahoo.com.cn
yuguanglou　　　 yuguanglou@21cn.com
fwolf　　　　　 fwolf001@tom.com
gavinguo　　　　 gavin@jqw.cn
cnhfyy（于洋）　cnhfyy@126.com
开心果 雨伞　　 webmaster@ehome.51.net

以上村民也可在喜悦国际村找到，欢迎所有喜欢PHP的朋友来本村学习、讨论（灌水？^_^）、。。。

自由　开源　团结　进步　喜悦国际村

Prev | Home
BUG | Up


Appendixes

Prev Next

IV. Appendixes [附录]

Table of Contents [内容列表]
17. Troubleshooting [疑难解答]
18. Tips & Tricks [使用技巧和经验]
19. Resources [相关资源]
20. BUGS [漏洞]
Prev | Home | Next
Inserts [插入] |  | [疑难解答] Troubleshooting


first

first is set to true if the current foreach iteration is the first one.

当前 foreach 循环第一次执行时 first 被设置成 true.

Prev | Home | Next
iteration | Up | last


iteration

iteration is used to display the current loop iteration.

iteration 用于显示当前循环的执行次数[待考]

Iteration always starts with 1 and is incremented by one one each iteration.

iteration 总是从 1 开始，每执行一次增加 1.[待考]

Prev | Home | Next
foreach,foreachelse | Up | first


last

last is set to true if the current foreach iteration is the last one.

当前 foreach 循环执行到最后一遍时 last 被设置成 true.

Prev | Home | Next
first | Up | show


show

show is used as a parameter to foreach. show is a boolean value, true or false. If false, the foreach will not be displayed. If there is a foreachelse present, that will be alternately displayed.

show 是 foreach 的一个参数. 取值为布尔值 true 或 false. 如果指定为 false 该循环不显示，如果循环指定了 foreachelse 子句，该子句显示与否也取决于 show 的取值.

Prev | Home | Next
last | Up | total


total

total is used to display the number of iterations that this foreach will loop. This can be used inside or after the foreach.

total 用于显示循环执行的次数，可以在循环中或循环执行后调用.

Prev | Home | Next
show | Up | include


Math

Prev Chapter 3. Basic Syntax[第3章.基本语法] Next

Math[数学运算]

Math can be applied directly to variable values.

数学运算可以直接应用到变量

Example 3-5. math examples

例 3-5.数学运算的例子

{$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`"}

Prev | Home | Next
Embedding Vars in Double Quotes [双引号里值的嵌入] | Up | Variables [变量]


Embedding Vars in Double Quotes

[双引号里值的嵌入]

Smarty will recognize assigned variables embedded in double quotes so long as the variables contain only numbers, letters, underscores and brackets []. With any other characters (period, object reference, etc.) the variable must be surrounded by backticks.

Smarty可以识别嵌入在双引号中的变量，只要此变量只包含数字、字母、下划线和中括号[].对于其他的符号（句号、对象相关的，等等）此变量必须用两个'`'(此符号和‘ ~ '在同一个键上，一般在ESC键下面一个键上)包住。

Example 3-4. embedded quotes syntax

例 3-4.双引号里值的嵌入语法

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

Prev | Home | Next
Attributes [属性] | Up | Math [数学运算]


$request_use_auto_globals

Prev Chapter 12. Variables
第十二章 变量 		Next

$request_use_auto_globals
自动全局变量

Specifies if Smarty should use php's $HTTP_*_VARS[] ($request_use_auto_globals=false which is the default value) or $_*[] ($request_use_auto_globals=true). This affects templates that make use of {$smarty.request.*}, {$smarty.get.*} etc. . Caution: If you set $request_use_auto_globals to true, variable.request.vars.order has no effect but php's configuration value gpc_order is used.
指定Smarty是否使用php的$HTTP_*_VARS[]数组变量(默认$request_use_auto_globals=false)或$_*[]数组($request_use_auto_globals=true)变量.这对使用了{$smarty.request.*}, {$smarty.get.*}等标记的模板有影响.值得注意的是:如果设置$request_use_auto_globals为真,variable.request.vars.order就无效了但php的gpc_order配置值还有作用.

Prev | Home | Next
$request_vars_order[变量顺序变量] | Up | [编译id变量]$compile_id