3 Author: Monte Ohrt <monte at ohrt dot com >
6 AN INTRODUCTION TO SMARTY 3
8 NOTICE FOR 3.1 release:
10 Please see the SMARTY_3.1_NOTES.txt file that comes with the distribution.
12 NOTICE for 3.0.5 release:
14 Smarty now follows the PHP error_reporting level by default. If PHP does not mask E_NOTICE and you try to access an unset template variable, you will now get an E_NOTICE warning. To revert to the old behavior:
16 $smarty->error_reporting = E_ALL & ~E_NOTICE;
18 NOTICE for 3.0 release:
20 IMPORTANT: Some API adjustments have been made between the RC4 and 3.0 release.
21 We felt it is better to make these now instead of after a 3.0 release, then have to
22 immediately deprecate APIs in 3.1. Online documentation has been updated
23 to reflect these changes. Specifically:
25 ---- API CHANGES RC4 -> 3.0 ----
28 $smarty->unregister->*
32 Have all been changed to local method calls such as:
34 $smarty->clearAllCache()
35 $smarty->registerFoo()
36 $smarty->unregisterFoo()
37 $smarty->testInstall()
40 Registration of function, block, compiler, and modifier plugins have been
41 consolidated under two API calls:
43 $smarty->registerPlugin(...)
44 $smarty->unregisterPlugin(...)
46 Registration of pre, post, output and variable filters have been
47 consolidated under two API calls:
49 $smarty->registerFilter(...)
50 $smarty->unregisterFilter(...)
52 Please refer to the online documentation for all specific changes:
54 http://www.smarty.net/documentation
58 The Smarty 3 API has been refactored to a syntax geared
59 for consistency and modularity. The Smarty 2 API syntax is still supported, but
60 will throw a deprecation notice. You can disable the notices, but it is highly
61 recommended to adjust your syntax to Smarty 3, as the Smarty 2 syntax must run
62 through an extra rerouting wrapper.
64 Basically, all Smarty methods now follow the "fooBarBaz" camel case syntax. Also,
65 all Smarty properties now have getters and setters. So for example, the property
66 $smarty->cache_dir can be set with $smarty->setCacheDir('foo/') and can be
67 retrieved with $smarty->getCacheDir().
69 Some of the Smarty 3 APIs have been revoked such as the "is*" methods that were
70 just duplicate functions of the now available "get*" methods.
72 Here is a rundown of the Smarty 3 API:
74 $smarty->fetch($template, $cache_id = null, $compile_id = null, $parent = null)
75 $smarty->display($template, $cache_id = null, $compile_id = null, $parent = null)
76 $smarty->isCached($template, $cache_id = null, $compile_id = null)
77 $smarty->createData($parent = null)
78 $smarty->createTemplate($template, $cache_id = null, $compile_id = null, $parent = null)
79 $smarty->enableSecurity()
80 $smarty->disableSecurity()
81 $smarty->setTemplateDir($template_dir)
82 $smarty->addTemplateDir($template_dir)
83 $smarty->templateExists($resource_name)
84 $smarty->loadPlugin($plugin_name, $check = true)
85 $smarty->loadFilter($type, $name)
86 $smarty->setExceptionHandler($handler)
87 $smarty->addPluginsDir($plugins_dir)
88 $smarty->getGlobal($varname = null)
89 $smarty->getRegisteredObject($name)
90 $smarty->getDebugTemplate()
91 $smarty->setDebugTemplate($tpl_name)
92 $smarty->assign($tpl_var, $value = null, $nocache = false)
93 $smarty->assignGlobal($varname, $value = null, $nocache = false)
94 $smarty->assignByRef($tpl_var, &$value, $nocache = false)
95 $smarty->append($tpl_var, $value = null, $merge = false, $nocache = false)
96 $smarty->appendByRef($tpl_var, &$value, $merge = false)
97 $smarty->clearAssign($tpl_var)
98 $smarty->clearAllAssign()
99 $smarty->configLoad($config_file, $sections = null)
100 $smarty->getVariable($variable, $_ptr = null, $search_parents = true, $error_enable = true)
101 $smarty->getConfigVariable($variable)
102 $smarty->getStreamVariable($variable)
103 $smarty->getConfigVars($varname = null)
104 $smarty->clearConfig($varname = null)
105 $smarty->getTemplateVars($varname = null, $_ptr = null, $search_parents = true)
106 $smarty->clearAllCache($exp_time = null, $type = null)
107 $smarty->clearCache($template_name, $cache_id = null, $compile_id = null, $exp_time = null, $type = null)
109 $smarty->registerPlugin($type, $tag, $callback, $cacheable = true, $cache_attr = array())
111 $smarty->registerObject($object_name, $object_impl, $allowed = array(), $smarty_args = true, $block_methods = array())
113 $smarty->registerFilter($type, $function_name)
114 $smarty->registerResource($resource_type, $function_names)
115 $smarty->registerDefaultPluginHandler($function_name)
116 $smarty->registerDefaultTemplateHandler($function_name)
118 $smarty->unregisterPlugin($type, $tag)
119 $smarty->unregisterObject($object_name)
120 $smarty->unregisterFilter($type, $function_name)
121 $smarty->unregisterResource($resource_type)
123 $smarty->compileAllTemplates($extension = '.tpl', $force_compile = false, $time_limit = 0, $max_errors = null)
124 $smarty->clearCompiledTemplate($resource_name = null, $compile_id = null, $exp_time = null)
125 $smarty->testInstall()
127 // then all the getters/setters, available for all properties. Here are a few:
129 $caching = $smarty->getCaching(); // get $smarty->caching
130 $smarty->setCaching(true); // set $smarty->caching
131 $smarty->setDeprecationNotices(false); // set $smarty->deprecation_notices
132 $smarty->setCacheId($id); // set $smarty->cache_id
133 $debugging = $smarty->getDebugging(); // get $smarty->debugging
138 The Smarty 3 file structure is similar to Smarty 2:
149 A lot of Smarty 3 core functionality lies in the sysplugins directory; you do
150 not need to change any files here. The /libs/plugins/ folder is where Smarty
151 plugins are located. You can add your own here, or create a separate plugin
152 directory, just the same as Smarty 2. You will still need to create your own
153 /cache/, /templates/, /templates_c/, /configs/ folders. Be sure /cache/ and
154 /templates_c/ are writable.
156 The typical way to use Smarty 3 should also look familiar:
158 require('Smarty.class.php');
159 $smarty = new Smarty;
160 $smarty->assign('foo','bar');
161 $smarty->display('index.tpl');
164 However, Smarty 3 works completely different on the inside. Smarty 3 is mostly
165 backward compatible with Smarty 2, except for the following items:
167 *) Smarty 3 is PHP 5 only. It will not work with PHP 4.
168 *) The {php} tag is disabled by default. Enable with $smarty->allow_php_tag=true.
169 *) Delimiters surrounded by whitespace are no longer treated as Smarty tags.
170 Therefore, { foo } will not compile as a tag, you must use {foo}. This change
171 Makes Javascript/CSS easier to work with, eliminating the need for {literal}.
172 This can be disabled by setting $smarty->auto_literal = false;
173 *) The Smarty 3 API is a bit different. Many Smarty 2 API calls are deprecated
174 but still work. You will want to update your calls to Smarty 3 for maximum
178 There are many things that are new to Smarty 3. Here are the notable items:
183 Smarty 3 now uses a lexing tokenizer for its parser/compiler. Basically, this
184 means Smarty has some syntax additions that make life easier such as in-template
185 math, shorter/intuitive function parameter options, infinite function recursion,
186 more accurate error handling, etc.
189 WHAT IS NEW IN SMARTY TEMPLATE SYNTAX
190 =====================================
192 Smarty 3 allows expressions almost anywhere. Expressions can include PHP
193 functions as long as they are not disabled by the security policy, object
194 methods and properties, etc. The {math} plugin is no longer necessary but
195 is still supported for BC.
198 {$x+$y} will output the sum of x and y.
199 {$foo = strlen($bar)} function in assignment
200 {assign var=foo value= $x+$y} in attributes
201 {$foo = myfunct( ($x+$y)*3 )} as function parameter
202 {$foo[$x+3]} as array index
204 Smarty tags can be used as values within other tags.
205 Example: {$foo={counter}+3}
207 Smarty tags can also be used inside double quoted strings.
208 Example: {$foo="this is message {counter}"}
210 You can define arrays within templates.
212 {assign var=foo value=[1,2,3]}
213 {assign var=foo value=['y'=>'yellow','b'=>'blue']}
214 Arrays can be nested.
215 {assign var=foo value=[1,[9,8],3]}
217 There is a new short syntax supported for assigning variables.
218 Example: {$foo=$bar+2}
220 You can assign a value to a specific array element. If the variable exists but
221 is not an array, it is converted to an array before the new values are assigned.
224 {$foo['bar']['blar']=1}
226 You can append values to an array. If the variable exists but is not an array,
227 it is converted to an array before the new values are assigned.
230 You can use a PHP-like syntax for accessing array elements, as well as the
231 original "dot" notation.
233 {$foo[1]} normal access
236 {$foo[$x+$x]} index may contain any expression
237 {$foo[$bar[1]]} nested index
238 {$foo[section_name]} smarty section access, not array access!
240 The original "dot" notation stays, and with improvements.
242 {$foo.a.b.c} => $foo['a']['b']['c']
243 {$foo.a.$b.c} => $foo['a'][$b]['c'] with variable index
244 {$foo.a.{$b+4}.c} => $foo['a'][$b+4]['c'] with expression as index
245 {$foo.a.{$b.c}} => $foo['a'][$b['c']] with nested index
247 note that { and } are used to address ambiguties when nesting the dot syntax.
249 Variable names themselves can be variable and contain expressions.
252 $foo_{$bar} variable name containing other variable
253 $foo_{$x+$y} variable name containing expressions
254 $foo_{$bar}_buh_{$blar} variable name with multiple segments
255 {$foo_{$x}} will output the variable $foo_1 if $x has a value of 1.
257 Object method chaining is implemented.
258 Example: {$object->method1($x)->method2($y)}
260 {for} tag added for looping (replacement for {section} tag):
261 {for $x=0, $y=count($foo); $x<$y; $x++} .... {/for}
262 Any number of statements can be used separated by comma as the first
263 inital expression at {for}.
265 {for $x = $start to $end step $step} ... {/for}is in the SVN now .
267 {for $x = $start to $end} ... {/for}
268 In this case the step value will be automaticall 1 or -1 depending on the start and end values.
269 Instead of $start and $end you can use any valid expression.
270 Inside the loop the following special vars can be accessed:
271 $x@iteration = number of iteration
272 $x@total = total number of iterations
273 $x@first = true on first iteration
274 $x@last = true on last iteration
277 The Smarty 2 {section} syntax is still supported.
279 New shorter {foreach} syntax to loop over an array.
280 Example: {foreach $myarray as $var}...{/foreach}
282 Within the foreach loop, properties are access via:
284 $var@key foreach $var array key
285 $var@iteration foreach current iteration count (1,2,3...)
286 $var@index foreach current index count (0,1,2...)
287 $var@total foreach $var array total
288 $var@first true on first iteration
289 $var@last true on last iteration
291 The Smarty 2 {foreach} tag syntax is still supported.
293 NOTE: {$bar[foo]} still indicates a variable inside of a {section} named foo.
294 If you want to access an array element with index foo, you must use quotes
295 such as {$bar['foo']}, or use the dot syntax {$bar.foo}.
297 while block tag is now implemented:
298 {while $foo}...{/while}
299 {while $x lt 10}...{/while}
301 Direct access to PHP functions:
302 Just as you can use PHP functions as modifiers directly, you can now access
303 PHP functions directly, provided they are permitted by security settings:
306 There is a new {function}...{/function} block tag to implement a template function.
307 This enables reuse of code sequences like a plugin function. It can call itself recursively.
308 Template function must be called with the new {call name=foo...} tag.
313 {function name=menu level=0}
314 <ul class="level{$level}">
315 {foreach $data as $entry}
316 {if is_array($entry)}
317 <li>{$entry@key}</li>
318 {call name=menu data=$entry level=$level+1}
326 {$menu = ['item1','item2','item3' => ['item3-1','item3-2','item3-3' =>
327 ['item3-3-1','item3-3-2']],'item4']}
329 {call name=menu data=$menu}
343 The function tag itself must have the "name" attribute. This name is the tag
344 name when calling the function. The function tag may have any number of
345 additional attributes. These will be default settings for local variables.
347 New {nocache} block function:
348 {nocache}...{/nocache} will declare a section of the template to be non-cached
349 when template caching is enabled.
351 New nocache attribute:
352 You can declare variable/function output as non-cached with the nocache attribute.
356 {$foo nocache} /* same */
358 {foo bar="baz" nocache=true}
359 {foo bar="baz" nocache} /* same */
361 {time() nocache=true}
362 {time() nocache} /* same */
364 Or you can also assign the variable in your script as nocache:
365 $smarty->assign('foo',$something,true); // third param is nocache setting
366 {$foo} /* non-cached */
368 $smarty.current_dir returns the directory name of the current template.
370 You can use strings directly as templates with the "string" resource type.
372 $smarty->display('string:This is my template, {$foo}!'); // php
373 {include file="string:This is my template, {$foo}!"} // template
377 VARIABLE SCOPE / VARIABLE STORAGE
378 =================================
380 In Smarty 2, all assigned variables were stored within the Smarty object.
381 Therefore, all variables assigned in PHP were accessible by all subsequent
382 fetch and display template calls.
384 In Smarty 3, we have the choice to assign variables to the main Smarty object,
385 to user-created data objects, and to user-created template objects.
386 These objects can be chained. The object at the end of a chain can access all
387 variables belonging to that template and all variables within the parent objects.
388 The Smarty object can only be the root of a chain, but a chain can be isolated
389 from the Smarty object.
391 All known Smarty assignment interfaces will work on the data and template objects.
393 Besides the above mentioned objects, there is also a special storage area for
396 A Smarty data object can be created as follows:
397 $data = $smarty->createData(); // create root data object
398 $data->assign('foo','bar'); // assign variables as usual
399 $data->config_load('my.conf'); // load config file
401 $data= $smarty->createData($smarty); // create data object having a parent link to
404 $data2= $smarty->createData($data); // create data object having a parent link to
405 the $data data object
407 A template object can be created by using the createTemplate method. It has the
408 same parameter assignments as the fetch() or display() method.
410 function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null)
412 The first parameter can be a template name, a smarty object or a data object.
415 $tpl = $smarty->createTemplate('mytpl.tpl'); // create template object not linked to any parent
416 $tpl->assign('foo','bar'); // directly assign variables
417 $tpl->config_load('my.conf'); // load config file
419 $tpl = $smarty->createTemplate('mytpl.tpl',$smarty); // create template having a parent link to the Smarty object
420 $tpl = $smarty->createTemplate('mytpl.tpl',$data); // create template having a parent link to the $data object
422 The standard fetch() and display() methods will implicitly create a template object.
423 If the $parent parameter is not specified in these method calls, the template object
424 is will link back to the Smarty object as it's parent.
426 If a template is called by an {include...} tag from another template, the
427 subtemplate links back to the calling template as it's parent.
429 All variables assigned locally or from a parent template are accessible. If the
430 template creates or modifies a variable by using the {assign var=foo...} or
431 {$foo=...} tags, these new values are only known locally (local scope). When the
432 template exits, none of the new variables or modifications can be seen in the
433 parent template(s). This is same behavior as in Smarty 2.
435 With Smarty 3, we can assign variables with a scope attribute which allows the
436 availablility of these new variables or modifications globally (ie in the parent
439 Possible scopes are local, parent, root and global.
441 {assign var=foo value='bar'} // no scope is specified, the default 'local'
442 {$foo='bar'} // same, local scope
443 {assign var=foo value='bar' scope='local'} // same, local scope
445 {assign var=foo value='bar' scope='parent'} // Values will be available to the parent object
446 {$foo='bar' scope='parent'} // (normally the calling template)
448 {assign var=foo value='bar' scope='root'} // Values will be exported up to the root object, so they can
449 {$foo='bar' scope='root'} // be seen from all templates using the same root.
451 {assign var=foo value='bar' scope='global'} // Values will be exported to global variable storage,
452 {$foo='bar' scope='global'} // they are available to any and all templates.
455 The scope attribute can also be attached to the {include...} tag. In this case,
456 the specified scope will be the default scope for all assignments within the
463 Smarty3 are following the same coding rules as in Smarty2.
464 The only difference is that the template object is passed as additional third parameter.
466 smarty_plugintype_name (array $params, object $smarty, object $template)
468 The Smarty 2 plugins are still compatible as long as they do not make use of specific Smarty2 internals.
471 TEMPLATE INHERITANCE:
472 =====================
474 With template inheritance you can define blocks, which are areas that can be
475 overriden by child templates, so your templates could look like this:
480 <title>{block name='title'}My site name{/block}</title>
483 <h1>{block name='page-title'}Default page title{/block}</h1>
485 {block name='content'}
493 {extends file='parent.tpl'}
499 {extends file='child.tpl'}
500 {block name='title'}Home - {$smarty.block.parent}{/block}
501 {block name='page-title'}My home{/block}
502 {block name='content'}
503 {foreach $images as $img}
504 <img src="{$img.url}" alt="{$img.description}" />
508 We redefined all the blocks here, however in the title block we used {$smarty.block.parent},
509 which tells Smarty to insert the default content from the parent template in its place.
510 The content block was overriden to display the image files, and page-title has also be
511 overriden to display a completely different title.
513 If we render grandchild.tpl we will get this:
516 <title>Home - Child title</title>
521 <img src="/example.jpg" alt="image" />
522 <img src="/example2.jpg" alt="image" />
523 <img src="/example3.jpg" alt="image" />
528 NOTE: In the child templates everything outside the {extends} or {block} tag sections
531 The inheritance tree can be as big as you want (meaning you can extend a file that
532 extends another one that extends another one and so on..), but be aware that all files
533 have to be checked for modifications at runtime so the more inheritance the more overhead you add.
535 Instead of defining the parent/child relationships with the {extends} tag in the child template you
536 can use the resource as follow:
538 $smarty->display('extends:parent.tpl|child.tpl|grandchild.tpl');
540 Child {block} tags may optionally have a append or prepend attribute. In this case the parent block content
541 is appended or prepended to the child block content.
543 {block name='title' append} My title {/block}
549 (see online documentation)
554 (see online documentation)
557 STATIC CLASS ACCESS AND NAMESPACE SUPPORT
558 =========================================
560 You can register a class with optional namespace for the use in the template like:
562 $smarty->register->templateClass('foo','name\name2\myclass');
564 In the template you can use it like this:
568 =======================
570 Please look through it and send any questions/suggestions/etc to the forums.
572 http://www.phpinsider.com/smarty-forum/viewtopic.php?t=14168