README 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. Smarty 3.1.11
  2. Author: Monte Ohrt <monte at ohrt dot com >
  3. Author: Uwe Tews
  4. AN INTRODUCTION TO SMARTY 3
  5. NOTICE FOR 3.1 release:
  6. Please see the SMARTY_3.1_NOTES.txt file that comes with the distribution.
  7. NOTICE for 3.0.5 release:
  8. 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:
  9. $smarty->error_reporting = E_ALL & ~E_NOTICE;
  10. NOTICE for 3.0 release:
  11. IMPORTANT: Some API adjustments have been made between the RC4 and 3.0 release.
  12. We felt it is better to make these now instead of after a 3.0 release, then have to
  13. immediately deprecate APIs in 3.1. Online documentation has been updated
  14. to reflect these changes. Specifically:
  15. ---- API CHANGES RC4 -> 3.0 ----
  16. $smarty->register->*
  17. $smarty->unregister->*
  18. $smarty->utility->*
  19. $samrty->cache->*
  20. Have all been changed to local method calls such as:
  21. $smarty->clearAllCache()
  22. $smarty->registerFoo()
  23. $smarty->unregisterFoo()
  24. $smarty->testInstall()
  25. etc.
  26. Registration of function, block, compiler, and modifier plugins have been
  27. consolidated under two API calls:
  28. $smarty->registerPlugin(...)
  29. $smarty->unregisterPlugin(...)
  30. Registration of pre, post, output and variable filters have been
  31. consolidated under two API calls:
  32. $smarty->registerFilter(...)
  33. $smarty->unregisterFilter(...)
  34. Please refer to the online documentation for all specific changes:
  35. http://www.smarty.net/documentation
  36. ----
  37. The Smarty 3 API has been refactored to a syntax geared
  38. for consistency and modularity. The Smarty 2 API syntax is still supported, but
  39. will throw a deprecation notice. You can disable the notices, but it is highly
  40. recommended to adjust your syntax to Smarty 3, as the Smarty 2 syntax must run
  41. through an extra rerouting wrapper.
  42. Basically, all Smarty methods now follow the "fooBarBaz" camel case syntax. Also,
  43. all Smarty properties now have getters and setters. So for example, the property
  44. $smarty->cache_dir can be set with $smarty->setCacheDir('foo/') and can be
  45. retrieved with $smarty->getCacheDir().
  46. Some of the Smarty 3 APIs have been revoked such as the "is*" methods that were
  47. just duplicate functions of the now available "get*" methods.
  48. Here is a rundown of the Smarty 3 API:
  49. $smarty->fetch($template, $cache_id = null, $compile_id = null, $parent = null)
  50. $smarty->display($template, $cache_id = null, $compile_id = null, $parent = null)
  51. $smarty->isCached($template, $cache_id = null, $compile_id = null)
  52. $smarty->createData($parent = null)
  53. $smarty->createTemplate($template, $cache_id = null, $compile_id = null, $parent = null)
  54. $smarty->enableSecurity()
  55. $smarty->disableSecurity()
  56. $smarty->setTemplateDir($template_dir)
  57. $smarty->addTemplateDir($template_dir)
  58. $smarty->templateExists($resource_name)
  59. $smarty->loadPlugin($plugin_name, $check = true)
  60. $smarty->loadFilter($type, $name)
  61. $smarty->setExceptionHandler($handler)
  62. $smarty->addPluginsDir($plugins_dir)
  63. $smarty->getGlobal($varname = null)
  64. $smarty->getRegisteredObject($name)
  65. $smarty->getDebugTemplate()
  66. $smarty->setDebugTemplate($tpl_name)
  67. $smarty->assign($tpl_var, $value = null, $nocache = false)
  68. $smarty->assignGlobal($varname, $value = null, $nocache = false)
  69. $smarty->assignByRef($tpl_var, &$value, $nocache = false)
  70. $smarty->append($tpl_var, $value = null, $merge = false, $nocache = false)
  71. $smarty->appendByRef($tpl_var, &$value, $merge = false)
  72. $smarty->clearAssign($tpl_var)
  73. $smarty->clearAllAssign()
  74. $smarty->configLoad($config_file, $sections = null)
  75. $smarty->getVariable($variable, $_ptr = null, $search_parents = true, $error_enable = true)
  76. $smarty->getConfigVariable($variable)
  77. $smarty->getStreamVariable($variable)
  78. $smarty->getConfigVars($varname = null)
  79. $smarty->clearConfig($varname = null)
  80. $smarty->getTemplateVars($varname = null, $_ptr = null, $search_parents = true)
  81. $smarty->clearAllCache($exp_time = null, $type = null)
  82. $smarty->clearCache($template_name, $cache_id = null, $compile_id = null, $exp_time = null, $type = null)
  83. $smarty->registerPlugin($type, $tag, $callback, $cacheable = true, $cache_attr = array())
  84. $smarty->registerObject($object_name, $object_impl, $allowed = array(), $smarty_args = true, $block_methods = array())
  85. $smarty->registerFilter($type, $function_name)
  86. $smarty->registerResource($resource_type, $function_names)
  87. $smarty->registerDefaultPluginHandler($function_name)
  88. $smarty->registerDefaultTemplateHandler($function_name)
  89. $smarty->unregisterPlugin($type, $tag)
  90. $smarty->unregisterObject($object_name)
  91. $smarty->unregisterFilter($type, $function_name)
  92. $smarty->unregisterResource($resource_type)
  93. $smarty->compileAllTemplates($extention = '.tpl', $force_compile = false, $time_limit = 0, $max_errors = null)
  94. $smarty->clearCompiledTemplate($resource_name = null, $compile_id = null, $exp_time = null)
  95. $smarty->testInstall()
  96. // then all the getters/setters, available for all properties. Here are a few:
  97. $caching = $smarty->getCaching(); // get $smarty->caching
  98. $smarty->setCaching(true); // set $smarty->caching
  99. $smarty->setDeprecationNotices(false); // set $smarty->deprecation_notices
  100. $smarty->setCacheId($id); // set $smarty->cache_id
  101. $debugging = $smarty->getDebugging(); // get $smarty->debugging
  102. FILE STRUCTURE
  103. The Smarty 3 file structure is similar to Smarty 2:
  104. /libs/
  105. Smarty.class.php
  106. /libs/sysplugins/
  107. internal.*
  108. /libs/plugins/
  109. function.mailto.php
  110. modifier.escape.php
  111. ...
  112. A lot of Smarty 3 core functionality lies in the sysplugins directory; you do
  113. not need to change any files here. The /libs/plugins/ folder is where Smarty
  114. plugins are located. You can add your own here, or create a separate plugin
  115. directory, just the same as Smarty 2. You will still need to create your own
  116. /cache/, /templates/, /templates_c/, /configs/ folders. Be sure /cache/ and
  117. /templates_c/ are writable.
  118. The typical way to use Smarty 3 should also look familiar:
  119. require('Smarty.class.php');
  120. $smarty = new Smarty;
  121. $smarty->assign('foo','bar');
  122. $smarty->display('index.tpl');
  123. However, Smarty 3 works completely different on the inside. Smarty 3 is mostly
  124. backward compatible with Smarty 2, except for the following items:
  125. *) Smarty 3 is PHP 5 only. It will not work with PHP 4.
  126. *) The {php} tag is disabled by default. Enable with $smarty->allow_php_tag=true.
  127. *) Delimiters surrounded by whitespace are no longer treated as Smarty tags.
  128. Therefore, { foo } will not compile as a tag, you must use {foo}. This change
  129. Makes Javascript/CSS easier to work with, eliminating the need for {literal}.
  130. This can be disabled by setting $smarty->auto_literal = false;
  131. *) The Smarty 3 API is a bit different. Many Smarty 2 API calls are deprecated
  132. but still work. You will want to update your calls to Smarty 3 for maximum
  133. efficiency.
  134. There are many things that are new to Smarty 3. Here are the notable items:
  135. LEXER/PARSER
  136. ============
  137. Smarty 3 now uses a lexing tokenizer for its parser/compiler. Basically, this
  138. means Smarty has some syntax additions that make life easier such as in-template
  139. math, shorter/intuitive function parameter options, infinite function recursion,
  140. more accurate error handling, etc.
  141. WHAT IS NEW IN SMARTY TEMPLATE SYNTAX
  142. =====================================
  143. Smarty 3 allows expressions almost anywhere. Expressions can include PHP
  144. functions as long as they are not disabled by the security policy, object
  145. methods and properties, etc. The {math} plugin is no longer necessary but
  146. is still supported for BC.
  147. Examples:
  148. {$x+$y} will output the sum of x and y.
  149. {$foo = strlen($bar)} function in assignment
  150. {assign var=foo value= $x+$y} in attributes
  151. {$foo = myfunct( ($x+$y)*3 )} as function parameter
  152. {$foo[$x+3]} as array index
  153. Smarty tags can be used as values within other tags.
  154. Example: {$foo={counter}+3}
  155. Smarty tags can also be used inside double quoted strings.
  156. Example: {$foo="this is message {counter}"}
  157. You can define arrays within templates.
  158. Examples:
  159. {assign var=foo value=[1,2,3]}
  160. {assign var=foo value=['y'=>'yellow','b'=>'blue']}
  161. Arrays can be nested.
  162. {assign var=foo value=[1,[9,8],3]}
  163. There is a new short syntax supported for assigning variables.
  164. Example: {$foo=$bar+2}
  165. You can assign a value to a specific array element. If the variable exists but
  166. is not an array, it is converted to an array before the new values are assigned.
  167. Examples:
  168. {$foo['bar']=1}
  169. {$foo['bar']['blar']=1}
  170. You can append values to an array. If the variable exists but is not an array,
  171. it is converted to an array before the new values are assigned.
  172. Example: {$foo[]=1}
  173. You can use a PHP-like syntax for accessing array elements, as well as the
  174. original "dot" notation.
  175. Examples:
  176. {$foo[1]} normal access
  177. {$foo['bar']}
  178. {$foo['bar'][1]}
  179. {$foo[$x+$x]} index may contain any expression
  180. {$foo[$bar[1]]} nested index
  181. {$foo[section_name]} smarty section access, not array access!
  182. The original "dot" notation stays, and with improvements.
  183. Examples:
  184. {$foo.a.b.c} => $foo['a']['b']['c']
  185. {$foo.a.$b.c} => $foo['a'][$b]['c'] with variable index
  186. {$foo.a.{$b+4}.c} => $foo['a'][$b+4]['c'] with expression as index
  187. {$foo.a.{$b.c}} => $foo['a'][$b['c']] with nested index
  188. note that { and } are used to address ambiguties when nesting the dot syntax.
  189. Variable names themselves can be variable and contain expressions.
  190. Examples:
  191. $foo normal variable
  192. $foo_{$bar} variable name containing other variable
  193. $foo_{$x+$y} variable name containing expressions
  194. $foo_{$bar}_buh_{$blar} variable name with multiple segments
  195. {$foo_{$x}} will output the variable $foo_1 if $x has a value of 1.
  196. Object method chaining is implemented.
  197. Example: {$object->method1($x)->method2($y)}
  198. {for} tag added for looping (replacement for {section} tag):
  199. {for $x=0, $y=count($foo); $x<$y; $x++} .... {/for}
  200. Any number of statements can be used separated by comma as the first
  201. inital expression at {for}.
  202. {for $x = $start to $end step $step} ... {/for}is in the SVN now .
  203. You can use also
  204. {for $x = $start to $end} ... {/for}
  205. In this case the step value will be automaticall 1 or -1 depending on the start and end values.
  206. Instead of $start and $end you can use any valid expression.
  207. Inside the loop the following special vars can be accessed:
  208. $x@iteration = number of iteration
  209. $x@total = total number of iterations
  210. $x@first = true on first iteration
  211. $x@last = true on last iteration
  212. The Smarty 2 {section} syntax is still supported.
  213. New shorter {foreach} syntax to loop over an array.
  214. Example: {foreach $myarray as $var}...{/foreach}
  215. Within the foreach loop, properties are access via:
  216. $var@key foreach $var array key
  217. $var@iteration foreach current iteration count (1,2,3...)
  218. $var@index foreach current index count (0,1,2...)
  219. $var@total foreach $var array total
  220. $var@first true on first iteration
  221. $var@last true on last iteration
  222. The Smarty 2 {foreach} tag syntax is still supported.
  223. NOTE: {$bar[foo]} still indicates a variable inside of a {section} named foo.
  224. If you want to access an array element with index foo, you must use quotes
  225. such as {$bar['foo']}, or use the dot syntax {$bar.foo}.
  226. while block tag is now implemented:
  227. {while $foo}...{/while}
  228. {while $x lt 10}...{/while}
  229. Direct access to PHP functions:
  230. Just as you can use PHP functions as modifiers directly, you can now access
  231. PHP functions directly, provided they are permitted by security settings:
  232. {time()}
  233. There is a new {function}...{/function} block tag to implement a template function.
  234. This enables reuse of code sequences like a plugin function. It can call itself recursively.
  235. Template function must be called with the new {call name=foo...} tag.
  236. Example:
  237. Template file:
  238. {function name=menu level=0}
  239. <ul class="level{$level}">
  240. {foreach $data as $entry}
  241. {if is_array($entry)}
  242. <li>{$entry@key}</li>
  243. {call name=menu data=$entry level=$level+1}
  244. {else}
  245. <li>{$entry}</li>
  246. {/if}
  247. {/foreach}
  248. </ul>
  249. {/function}
  250. {$menu = ['item1','item2','item3' => ['item3-1','item3-2','item3-3' =>
  251. ['item3-3-1','item3-3-2']],'item4']}
  252. {call name=menu data=$menu}
  253. Generated output:
  254. * item1
  255. * item2
  256. * item3
  257. o item3-1
  258. o item3-2
  259. o item3-3
  260. + item3-3-1
  261. + item3-3-2
  262. * item4
  263. The function tag itself must have the "name" attribute. This name is the tag
  264. name when calling the function. The function tag may have any number of
  265. additional attributes. These will be default settings for local variables.
  266. New {nocache} block function:
  267. {nocache}...{/nocache} will declare a section of the template to be non-cached
  268. when template caching is enabled.
  269. New nocache attribute:
  270. You can declare variable/function output as non-cached with the nocache attribute.
  271. Examples:
  272. {$foo nocache=true}
  273. {$foo nocache} /* same */
  274. {foo bar="baz" nocache=true}
  275. {foo bar="baz" nocache} /* same */
  276. {time() nocache=true}
  277. {time() nocache} /* same */
  278. Or you can also assign the variable in your script as nocache:
  279. $smarty->assign('foo',$something,true); // third param is nocache setting
  280. {$foo} /* non-cached */
  281. $smarty.current_dir returns the directory name of the current template.
  282. You can use strings directly as templates with the "string" resource type.
  283. Examples:
  284. $smarty->display('string:This is my template, {$foo}!'); // php
  285. {include file="string:This is my template, {$foo}!"} // template
  286. VARIABLE SCOPE / VARIABLE STORAGE
  287. =================================
  288. In Smarty 2, all assigned variables were stored within the Smarty object.
  289. Therefore, all variables assigned in PHP were accessible by all subsequent
  290. fetch and display template calls.
  291. In Smarty 3, we have the choice to assign variables to the main Smarty object,
  292. to user-created data objects, and to user-created template objects.
  293. These objects can be chained. The object at the end of a chain can access all
  294. variables belonging to that template and all variables within the parent objects.
  295. The Smarty object can only be the root of a chain, but a chain can be isolated
  296. from the Smarty object.
  297. All known Smarty assignment interfaces will work on the data and template objects.
  298. Besides the above mentioned objects, there is also a special storage area for
  299. global variables.
  300. A Smarty data object can be created as follows:
  301. $data = $smarty->createData(); // create root data object
  302. $data->assign('foo','bar'); // assign variables as usual
  303. $data->config_load('my.conf'); // load config file
  304. $data= $smarty->createData($smarty); // create data object having a parent link to
  305. the Smarty object
  306. $data2= $smarty->createData($data); // create data object having a parent link to
  307. the $data data object
  308. A template object can be created by using the createTemplate method. It has the
  309. same parameter assignments as the fetch() or display() method.
  310. Function definition:
  311. function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null)
  312. The first parameter can be a template name, a smarty object or a data object.
  313. Examples:
  314. $tpl = $smarty->createTemplate('mytpl.tpl'); // create template object not linked to any parent
  315. $tpl->assign('foo','bar'); // directly assign variables
  316. $tpl->config_load('my.conf'); // load config file
  317. $tpl = $smarty->createTemplate('mytpl.tpl',$smarty); // create template having a parent link to the Smarty object
  318. $tpl = $smarty->createTemplate('mytpl.tpl',$data); // create template having a parent link to the $data object
  319. The standard fetch() and display() methods will implicitly create a template object.
  320. If the $parent parameter is not specified in these method calls, the template object
  321. is will link back to the Smarty object as it's parent.
  322. If a template is called by an {include...} tag from another template, the
  323. subtemplate links back to the calling template as it's parent.
  324. All variables assigned locally or from a parent template are accessible. If the
  325. template creates or modifies a variable by using the {assign var=foo...} or
  326. {$foo=...} tags, these new values are only known locally (local scope). When the
  327. template exits, none of the new variables or modifications can be seen in the
  328. parent template(s). This is same behavior as in Smarty 2.
  329. With Smarty 3, we can assign variables with a scope attribute which allows the
  330. availablility of these new variables or modifications globally (ie in the parent
  331. templates.)
  332. Possible scopes are local, parent, root and global.
  333. Examples:
  334. {assign var=foo value='bar'} // no scope is specified, the default 'local'
  335. {$foo='bar'} // same, local scope
  336. {assign var=foo value='bar' scope='local'} // same, local scope
  337. {assign var=foo value='bar' scope='parent'} // Values will be available to the parent object
  338. {$foo='bar' scope='parent'} // (normally the calling template)
  339. {assign var=foo value='bar' scope='root'} // Values will be exported up to the root object, so they can
  340. {$foo='bar' scope='root'} // be seen from all templates using the same root.
  341. {assign var=foo value='bar' scope='global'} // Values will be exported to global variable storage,
  342. {$foo='bar' scope='global'} // they are available to any and all templates.
  343. The scope attribute can also be attached to the {include...} tag. In this case,
  344. the specified scope will be the default scope for all assignments within the
  345. included template.
  346. PLUGINS
  347. =======
  348. Smarty3 are following the same coding rules as in Smarty2.
  349. The only difference is that the template object is passed as additional third parameter.
  350. smarty_plugintype_name (array $params, object $smarty, object $template)
  351. The Smarty 2 plugins are still compatible as long as they do not make use of specific Smarty2 internals.
  352. TEMPLATE INHERITANCE:
  353. =====================
  354. With template inheritance you can define blocks, which are areas that can be
  355. overriden by child templates, so your templates could look like this:
  356. parent.tpl:
  357. <html>
  358. <head>
  359. <title>{block name='title'}My site name{/block}</title>
  360. </head>
  361. <body>
  362. <h1>{block name='page-title'}Default page title{/block}</h1>
  363. <div id="content">
  364. {block name='content'}
  365. Default content
  366. {/block}
  367. </div>
  368. </body>
  369. </html>
  370. child.tpl:
  371. {extends file='parent.tpl'}
  372. {block name='title'}
  373. Child title
  374. {/block}
  375. grandchild.tpl:
  376. {extends file='child.tpl'}
  377. {block name='title'}Home - {$smarty.block.parent}{/block}
  378. {block name='page-title'}My home{/block}
  379. {block name='content'}
  380. {foreach $images as $img}
  381. <img src="{$img.url}" alt="{$img.description}" />
  382. {/foreach}
  383. {/block}
  384. We redefined all the blocks here, however in the title block we used {$smarty.block.parent},
  385. which tells Smarty to insert the default content from the parent template in its place.
  386. The content block was overriden to display the image files, and page-title has also be
  387. overriden to display a completely different title.
  388. If we render grandchild.tpl we will get this:
  389. <html>
  390. <head>
  391. <title>Home - Child title</title>
  392. </head>
  393. <body>
  394. <h1>My home</h1>
  395. <div id="content">
  396. <img src="/example.jpg" alt="image" />
  397. <img src="/example2.jpg" alt="image" />
  398. <img src="/example3.jpg" alt="image" />
  399. </div>
  400. </body>
  401. </html>
  402. NOTE: In the child templates everything outside the {extends} or {block} tag sections
  403. is ignored.
  404. The inheritance tree can be as big as you want (meaning you can extend a file that
  405. extends another one that extends another one and so on..), but be aware that all files
  406. have to be checked for modifications at runtime so the more inheritance the more overhead you add.
  407. Instead of defining the parent/child relationships with the {extends} tag in the child template you
  408. can use the resource as follow:
  409. $smarty->display('extends:parent.tpl|child.tpl|grandchild.tpl');
  410. Child {block} tags may optionally have a append or prepend attribute. In this case the parent block content
  411. is appended or prepended to the child block content.
  412. {block name='title' append} My title {/block}
  413. PHP STREAMS:
  414. ============
  415. (see online documentation)
  416. VARIBLE FILTERS:
  417. ================
  418. (see online documentation)
  419. STATIC CLASS ACCESS AND NAMESPACE SUPPORT
  420. =========================================
  421. You can register a class with optional namespace for the use in the template like:
  422. $smarty->register->templateClass('foo','name\name2\myclass');
  423. In the template you can use it like this:
  424. {foo::method()} etc.
  425. =======================
  426. Please look through it and send any questions/suggestions/etc to the forums.
  427. http://www.phpinsider.com/smarty-forum/viewtopic.php?t=14168
  428. Monte and Uwe