Smarty3.0 配置方法及初步认识

今天想通过用Smarty作一个东东,准备到官网去下一个最新的版本下来。

没曾想Smarty出了3.0版本了,目前已经到3.0.8

当下弄下来折腾一下,看看有什么好东西

这里大概解读一下附带的README文件

BETA8 需要注意的事情
Smarty3 的API已经被重构过以更好的面向结构话和语法一致性。但是Smarty2的API仍然是支持的,但是会出提示。

当然,也可以手动disable掉这个提示,但是强烈推荐你将你的语法升级到适应Smarty3的语法

Smarty3中所有的方法命名都采用”fooBarBaz”的方式,而且,所有的Smarty属性都含有getters和setters,举例:

老版本中设置Cache的路径

$smarty->cache_dir
现在可以这样作:

$smarty->setCacheDir('foo/')
并且可以通过如下方法获取:

$smarty->getCacheDir()
目录结构
index.php
/libs/
Smarty.class.php #主文件
/libs/sysplugins/ #内部plugin
internal.
/plugins/ #外部plugin,可自由扩充
function.mailto.php
modifier.escape.php2
/templates/ #模板,可以是纯php或传统的smarty模板
index.tpl
index_view.php
简单调用
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('foo','bar');
$smarty->display('index.tpl');)))
区别
虽然Smarty3在模板使用起来和以前没有区别,但是其实内部逻辑是截然不同的,却也是能够和2进行兼容

除了以下几点

Smarty3只能运行在PHP5环境下,不再支持PHP4
{php}标签默认是关闭的,可以通过如下方式打开

$smarty->allow_php_tag=true

模板标签将不支持空格,如{ $abc }在Smarty2中可以识别的,但是3里头就不行了,必须这样{$abc},这样是为了能够更好的支持javascript和css

Smarty3的API有一定的不同,但是仍然支持Smarty2
新的功能
表达式
支持更加随意的表达式

{$x+$y} 输入x和y的和
{$foo = strlen($bar)} 变量支持PHP函数
{assign var=foo value= $x+$y} 属性支持表达式
{$foo = myfunct( ($x+$y)*3 )} 函数参数支持表达式
{$foo[$x+3]} 数组下表支持表达式
引号中可以使用变量

{$foo="this is message {counter}"}
可以在模板里头定义数组

{assign var=foo value=[1,2,3]}
{assign var=foo value=['y'=>'yellow','b'=>'blue']}
{assign var=foo value=[1,[9,8],3]}
简单的变量赋值

{$foo=$bar+2}
可以给指定的数组元素赋值,如果变量存在但不是数组,会先转换成数组,再进行赋值

{$foo['bar']=1}
{$foo['bar']['blar']=1}
同上,可以给数组添加值

{$foo[]=1}
对象的属性支持”.”操作符

{$foo.a.b.c} => $foo['a']['b']['c']
{$foo.a.$b.c} => $foo['a'][$b]['c']
{$foo.a.{$b+4}.c} => $foo['a'][$b+4]['c']
{$foo.a.{$b.c}} => $foo['a'][$b['c']]
变量名中支持变量

$foo 一个普通的变量
$foo_{$bar} 变量名中包含变量
$foo_{$x+$y} 变量名中可以支持表达式
$foo_{$bar}_buh_{$blar} 变量名包含多个变量
{$foo_{$x}} 如果$x是1,则输出$foo_1
支持对象链,即是对象方法的连续调用,很像jquery

{$object->method1($x)->method2($y)}
{for}标签支持类似loop一样的循环

{for $x=0, $y=count($foo); $x<$y; $x++} .... {/for}
在FOR循环中可以通过如下特殊标示符限定位置:

$x@iteration 当前循环次数
$x@total 总循环次数
$x@first 循环第一次
$x@last 循环最后一次
新的foreach语法

{foreach $myarray as $var}...{/foreach}
同样是foreach里头的特殊表示符,看的就明白,不翻译了……

$var@key foreach $var array key
$var@iteration foreach current iteration count (1,2,3...)
$var@index foreach current index count (0,1,2...)
$var@total foreach $var array total
$var@first true on first iteration
$var@last true on last iteration
支持while循环

{while $foo}...{/while}
{while $x lt 10}...{/while}
可以直接使用PHP的函数

{time()}
新增加了一个{function}的标签,可以定义一个可供调用的函数块(我喜欢这功能,哈哈!)

{function}...{/function}
该标签必须有一个name属性,用来指名该函数名称,也是调用的时候需要用到的

下面是一个例子

/* 定义一个函数 */
{function name=menu level=0}
<ul class="level{$level}">
{foreach $data as $entry}
{if is_array($entry)}
<li>{$entry@key}</li>
{menu data=$entry level=$level+1}
{else}
<li>{$entry}</li>
{/if}
{/foreach}
</ul>
{/function}

/* 给函数传递的参数 */
{$menu = ['item1','item2','item3' => ['item3-1','item3-2','item3-3' =>
['item3-3-1','item3-3-2']],'item4']}

/* 调用那个函数 */
{menu data=$menu}
代码块不缓存,可以使用{nocache}标签默认是关闭的

{nocache} ... {/nocache}
还可以作为属性

{$foo nocache=true}
{$foo nocache}
{foo bar="baz" nocache=true}
{foo bar="baz" nocache}
{time() nocache=true}
{time() nocache}
返回当前模板的方法

$smarty.cur_template
变量作用域和存储
在Smarty2中,所有的变量都存储在Smarty对象中,因此所有的变量在所有模板和子方法中都可以获取

在Smarty3中,可以自己定义的将变量存储在主Smarty对象中,或者用户自己定义的对象中,甚至是用户自己的模板对象中

而且这些对象可以通过链式串接起来。

在链的末尾的对象可以获取到对象链之前的对象中存储的所有变量。

Smarty对象必须是链的根对象,但是对象链却是可以独立于Smarty对象存在的

所有的Smarty的赋值方法都可以用在data对象或者模板对象

除了上面说几个方面,全局变量还有一种特殊的存储方式

一个Smarty的数据对象(data Object)可以通过如下方式创建

$data = $smarty->createData(); // 创建根数据对象
$data->assign('foo','bar'); // 赋值操作
$data->config_load('my.conf'); // 加载配置文件

$data = $smarty->createData($smarty); // 以Smarty作为父对象,创建数据对象

$data2= $smarty->createData($data); // 以data作为父对象,创建数据对象data2
创建一个模板对象(template object) 可以通过createTemplate方法,它的参数传递和fetch()/display()方法一致

函数定义方式

function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null)
举例

$tpl = $smarty->createTemplate('mytpl.tpl'); // 创建一个模板对象,没有父对象
$tpl->assign('foo','bar'); // directly assign variables
$tpl->config_load('my.conf');

$tpl = $smarty->createTemplate('mytpl.tpl',$smarty); // 以Smarty为父对象,创建模板对象
fetch()/display() 两个方法将隐式的创建一个模板对象

如果不指定父对象,则默认父对象将指向Smarty对象

如果一个模板是通过include方式调用的,则子模板的父对象将指向引用它的模板对象

所有当前模板变量和父对象的模板对象都是可以获取的,但是如果是通过{assign}或者{$foo=…}这样的方法创建或者修改变量

则它的作用域将只停留在当前模板对象

Smarty3中,在赋值变量的时候可以指定它的作用域,有4个值local,parent,root,global

{assign var=foo value='bar'} // no scope is specified, the default 'local'
{$foo='bar'} // same, local scope
{assign var=foo value='bar' scope='local'} // same, local scope
{assign var=foo value='bar' scope='parent'} // Values will be available to the parent object
{$foo='bar' scope='parent'} // (normally the calling template)
{assign var=foo value='bar' scope='root'} // Values will be exported up to the root object, so they can
{$foo='bar' scope='root'} // be seen from all templates using the same root.
{assign var=foo value='bar' scope='global'} // Values will be exported to global variable storage,
{$foo='bar' scope='global'}
扩展
Smarty3的扩展都是继承至Smarty – Internal – PluginBase的类

所有的扩展都包含一个Smarty对象实例的$this->smarty属性

模板继承
你可以在模板中写{block} … {/block}快,并且这些块可以在子模板中进行覆盖

parent.tpl:

<html>
<head>
<title>{block name='title'}My site name{/block}</title>
</head>
<body>
<h1>{block name='page-title'}Default page title{/block}</h1>
<div id="content">
{block name='content'}
Default content
{/block}
</div>
</body>
</html>
child.tpl:

{extends file='parent.tpl'}

{block name='title'}
Child title
{/block}
grandchild.tpl:

{extends file='child.tpl'}

{block name='title'}Home - {$smarty.block.parent}{/block}
{block name='page-title'}My home{/block}
{block name='content'}
{foreach $images as $img}
<img src="{$img.url}" alt="{$img.description}" />
{/foreach}
{/block}
可以通过extends标签来指定被继承的模板,并在子模板中通过重写父模板的同名block块,达到覆盖的目的

同时,可以通过{$smarty.block,parent}获取到父block的内容

上面的grandchild.tpl将生成如下内容

<html>
<head>
<title>Home - Child title</title>
</head>
<body>
<h1>My home</h1>
<div id="content">
<img src="/example.jpg" alt="image" />
<img src="/example2.jpg" alt="image" />
<img src="/example3.jpg" alt="image" />
</div>
</body>
</html>
注意,在子模板中,所有在{block} … {/block}之外的内容都将被忽略

这种继承支持多文件,多重继承,意味着可以无线的继承下去

还可通过{block}的append和prepend属性来插入父模板结构中

PHP 流
待补充…

变量过滤
待补充…

PHP 模板
对于那些希望在模板中纯粹写PHP的人员来说,Smarty提供了一个php的选项,纯PHP和有以下几个不同的地方:

PHP模板将不进行编译,直接被引擎调用
PHP模板将不具备任何安全属性
Smarty默认不开启PHP模板,可以$smarty->allow_php_templates=true来打开

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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 翻译人员列表

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值