21-05-2004
Copyright © 2001-2004 ispi of Lincoln, Inc.
Оригинал: smarty.php.net
След. | ||
Предисловие |
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.
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.
Пред. | Начало | След. |
Cache Groups | Уровень выше | Prefilters |
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.
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.
Пример 15-4. using a template outputfilter
|
Пред. | Начало | След. |
Postfilters | Уровень выше | Cache Handler Function |
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.
Пример 15-3. using a template postfilter
|
Пред. | Начало | След. |
Prefilters | Уровень выше | Output Filters |
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.
Пример 15-2. using a template prefilter
|
Пред. | Начало | След. |
Advanced Features | Уровень выше | Postfilters |
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.
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.
Пред. | Начало | След. |
Methods | Уровень выше | assign |
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.
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 | Уровень выше | clear_all_assign |
This is used to assign values to the templates. You can explicitly pass name/value pairs, or associative arrays containing the name/value pairs.
Пред. | Начало | След. |
append_by_ref | Уровень выше | assign_by_ref |
Пред. | Начало | След. |
assign_by_ref | Уровень выше | clear_all_cache |
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.
Пред. | Начало | След. |
clear_all_assign | Уровень выше | clear_assign |
This clears the value of an assigned variable. This can be a single value, or an array of values.
Пред. | Начало | След. |
clear_all_cache | Уровень выше | clear_cache |
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.
Пред. | Начало | След. |
clear_assign | Уровень выше | clear_compiled_tpl |
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.
Пред. | Начало | След. |
clear_cache | Уровень выше | clear_config |
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.
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().
Пример 13-14. fetch
|
Пред. | Начало | След. |
display | Уровень выше | get_config_vars |
This clears all assigned config variables. If a variable name is supplied, only that variable is cleared.
Пред. | Начало | След. |
clear_compiled_tpl | Уровень выше | config_load |
This loads config file data and assigns it to the template. This works identical to the template config_load function.
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.
Пред. | Начало | След. |
clear_config | Уровень выше | display |
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().
Пример 13-12. display
|
Use the syntax for template resources to display files outside of the $template_dir directory.
Пример 13-13. function display template resource examples
|
Пред. | Начало | След. |
config_load | Уровень выше | fetch |
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.
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.
Пред. | Начало | След. |
$default_modifiers | Уровень выше | append_by_ref |
This returns the given loaded config variable value. If no parameter is given, an array of all loaded config variables is returned.
Пред. | Начало | След. |
fetch | Уровень выше | get_registered_object |
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.
Пред. | Начало | След. |
get_config_vars | Уровень выше | get_template_vars |
This returns the given assigned variable value. If no parameter is given, an array of all assigned variables is returned.
Пред. | Начало | След. |
get_registered_object | Уровень выше | is_cached |
This returns true if there is a valid cache for this template. This only works if caching is set to true.
You can also pass a cache id as an optional second parameter in case you want multiple caches for the given template.
Пред. | Начало | След. |
get_template_vars | Уровень выше | load_filter |
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'.
Пред. | Начало | След. |
is_cached | Уровень выше | register_block |
Use this to dynamically register block functions plugins. Pass in the block function name, followed by the PHP function name that implements it.
Пример 13-21. register_block
|
Пред. | Начало | След. |
load_filter | Уровень выше | register_compiler_function |
Use this to dynamically register a compiler function plugin. Pass in the compiler function name, followed by the PHP function that implements it.
Пред. | Начало | След. |
register_block | Уровень выше | register_function |
Use this to dynamically register template function plugins. Pass in the template function name, followed by the PHP function name that implements it.
Пример 13-22. register_function
|
Пред. | Начало | След. |
register_compiler_function | Уровень выше | register_modifier |
Use this to dynamically register modifier plugin. Pass in the template modifier name, followed by the PHP function that it implements it.
Пред. | Начало | След. |
register_function | Уровень выше | register_object |
void register_object
(string object_name, object $object, array allowed methods/properties, boolean format)
This is to register an object for use in the templates. See the object section of the manual for examples.
Пред. | Начало | След. |
register_modifier | Уровень выше | register_outputfilter |
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.
Пред. | Начало | След. |
register_postfilter | Уровень выше | register_resource |
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.
Пред. | Начало | След. |
register_object | Уровень выше | register_postfilter |
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.
Пред. | Начало | След. |
register_outputfilter | Уровень выше | register_prefilter |
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.
Пред. | Начало | След. |
register_prefilter | Уровень выше | trigger_error |
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.
Пред. | Начало | След. |
trigger_error | Уровень выше | unregister_block |
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.
Пред. | Начало | След. |
register_resource | Уровень выше | template_exists |
Use this to dynamically unregister block function plugin. Pass in the block function name.
Пред. | Начало | След. |
template_exists | Уровень выше | unregister_compiler_function |
Use this to dynamically unregister a compiler function. Pass in the name of the compiler function.
Пред. | Начало | След. |
unregister_block | Уровень выше | unregister_function |
Use this to dynamically unregister template function plugin. Pass in the template function name.
Пред. | Начало | След. |
unregister_compiler_function | Уровень выше | unregister_modifier |
Use this to dynamically unregister modifier plugin. Pass in the template modifier name.
Пред. | Начало | След. |
unregister_function | Уровень выше | unregister_object |
Пред. | Начало | След. |
unregister_modifier | Уровень выше | unregister_outputfilter |
Пред. | Начало | След. |
unregister_object | Уровень выше | unregister_postfilter |
Пред. | Начало | След. |
unregister_outputfilter | Уровень выше | unregister_prefilter |
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.
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.
The first thing to do is enable caching. This is done by setting $caching = true (or 1.)
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.
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!
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.
Пример 14-2. setting cache_lifetime per cache
|
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.
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.)
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.
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.
You can clear all the cache files with the clear_all_cache() function, or individual cache files (or groups) with the clear_cache() function.
Пред. | Начало | След. |
unregister_resource | Уровень выше | Multiple Caches Per Page |
Руководство по Smarty | ||
---|---|---|
Пред. |
Смотрите файл BUGS, который поставляется вместе с стандартной поставко Smarty или ищите список на сайте.
Пред. | Начало | |
Источники | Уровень выше |
Пред. | Начало | След. |
unregister_postfilter | Уровень выше | unregister_resource |
Use this to dynamically unregister a resource plugin. Pass in the name of the resource.
Пред. | Начало | След. |
unregister_prefilter | Уровень выше | Caching |
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.
Technical Note: It is not recommended to put this directory under the web server document root.
Пред. | Начало | След. |
Constants | Уровень выше | $compile_dir |
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.
Пример 14-9. cache_id groups
|
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');
Пред. | Начало | След. |
Multiple Caches Per Page | Уровень выше | Advanced Features |
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.
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.
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!
Be sure to pass the same cache_id as the second parameter to is_cached() and clear_cache().
Пример 14-7. passing a cache_id to is_cached()
|
You can clear all caches for a particular cache_id by passing null as the first parameter to clear_cache().
In this manner, you can "group" your caches together by giving them the same cache_id.
Пред. | Начало | След. |
Caching | Уровень выше | Cache Groups |
В Smarty включена консоль для отладки. Консоль позволяет узнать все включенные файлы, присвоенные переменные и настройки из конфигурационных файлов. Шаблон "debug.tpl", поставляемый вместе со Smarty, управляет видом консоли. Установите опцию Smarty $debugging в true и, если надо, укажите в $debug_tpl путь к шаблону debug.tpl (по умолчанию это SMARTY_DIR). Когда вы загружаете страницу, должно появиться всплывающие окно и вывести консоль отладки. Для вывода доступных переменных из конкретного шаблона, см. функцию {debug}. Для отключения консоли отладки, установите $debugging в false. Можно также опционально включить консоль отладки, добавив SMARTY_DEBUG в URL, если включена опция $debugging_ctrl.
Замечание: Консоль отладки не работает, когда используется функция API fetch(). Необходимо использовать только функцию display(). Она генерирует javascript код вначале каждой сгенерированной страницы. Если вам не нравится javascript, можно отредатировать debug.tpl для изменения способа отображения по вашему вкусу. Отладочная информация не кэшируется и в отладочную информацию не включается информация о debug.tpl.
Замечание: Время загрузки каждого шаблона и файла конфигурации выводятся в секундах или в миллисекундах.
Пред. | Начало | След. |
Конфигурационные файлы | Уровень выше | Smarty для программистов |
С помощью конфигурационных файлов дизайнеру удобно управлять глобальными переменными из одного файлаю. Например, цветами в шаблонах. Обычно, если вы хотите сменить цветувую схему, то необходимо просмотреть каждый шаблон и в каждом изменить цвета. С помощью файла конфигурации все цвета могут быть вынесены в отдельный файл и только один файл надо будет исправлять.
Пример 9-1. Пример файла конфигурации
|
Значения переменных могут заключаться в кавычки, но это не обязательно. Можно использовать как двойные, так и одинарные кавычки. Если у вас есть значение, которое занимает больше, чем одну строку, необходимо заключить его в тройные кавычки ("""). Можно включать комментарии в файл конфигурации используя любой синтакис, который не является допустимым синтаксисом файлов конфигурации. Рекомендуется использовать символ # (hash) в начале строки.
Конфигурационный файл в примере имеет две секции. Названия секций заключены в квадратные скобки []. Названия секций могут быть произвольными строками, не содержащими символов [ или ]. Четыре переменные вначале - глобальные переменные или переменные вне секций. Эти переменные всегда загружаются из файла конфигурации. Если загружается определенная секция, то глобальные переменные и переменные из этой секции становятся доступными. Если переменная существует как глобальная, так и внутри секции, то используется версия из секции. Если есть две одинаковые переменные в пределах одной секции, то используеться последний встретившийся вариант.
Файлы конфигурации загружаются в шаблон в помощью функции config_load.
Можно спрятать отдельные переменные или целые секции, добавив к названию точку в начале. Это полезно, когда ваше приложение берет некоторые переменные, ненужные в шаблоне, из файла конфигурации. Если шаблоны могут редактировать третьи лица, то вы можете быть спокойны за ценную информацию из файлов конфигураций: они не смогут ее загрузить в шаблон.
Пред. | Начало | След. |
textformat | Уровень выше | Отладочная консоль |
Пред. | Начало | След. |
Что такое Smarty? | Уровень выше | Базовая инсталяция |
Инсталируйте библиотечный файлы Smarty, которые анаходятся в папке /libs/ дистрибутива. Вы НЕ ДОЛЖНЫ редактировать эти файлы. Они разделены среди всех приложений и могут изменяться только при обновлении Smarty.
Smarty использует PHP константу SMARTY_DIR, которая указывает путь к библиотечным файлам Smarty. Обычно, если приложение может найти файл Smarty.class.php , то нет необходимости устанавливать SMARTY_DIR, Иначе, если Smarty.class.php не в вашем include_path, или вы не указывали абсолютный путь к нему в приложении, то вы должны определить SMARTY_DIR вручную. SMARTY_DIR должен включать завершающий слэш.
Как надо создавать обект Smarty в ваших PHP сценариях:
Попробуйте выполнить вышеупомянутый сценарий. Если Вы получаете ошибку о том, что Smarty.class.php не найден, вы должны селать одно из следующего:
Теперь, когда библиотечные файлы находятся на месте, пришло время установка каталоги Smarty для вашего приложения. Smarty требует четыре каталога, которые (по умолчанию) называются templates , templates_c , configs и cache . Каждый из них определяем свойствами класса Smarty $template_dir , $compile_dir , $config_dir , и $cache_dir соответственно. Очень рекомендуется, чтобы вы устанавливали отдельные наборы этих каталогов для каждого приложения, которое будет использовать Smarty.
Убедитесь, что Вы знаете расположение вашего корня документа на веб сервере. В нашем примере, корень документа - "/web/www.mydomain.com/docs/". К каталогам Smarty обращается только библиотека Смарти и никогда не обращает непосредственно web-браузером. Поэтому, чтобы избежать любых предприятий(беспокойств) защиты, рекомендует разместить эти каталоги в каталог от корня документа. 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 in a directory off the document root.
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/".
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/". 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.)
Lets take a look at the file structure so far:
Пример 2-6. Example file structure
|
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.
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.
We need to create the index.tpl file that Smarty will load. This will be located in your $template_dir.
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.
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.
Пример 2-9. Editing /web/www.mydomain.com/docs/guestbook/index.php
|
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.
Now load the index.php file from your web browser. You should see "Hello, Ned!"
You have completed the basic setup for Smarty!
Пред. | Начало | След. |
Инсталяция | Уровень выше | 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.
Пример 2-10. Editing /php/includes/guestbook/setup.php
|
Now lets alter the index.php file to use setup.php:
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 располагаются между специальными разделителями. По умолчанию это { и }, но они могут быть изменены.
Для наших примеров мы будем использовать стандартные разделители. Smarty все содержимое вне разделителей отображает как статическое содержание, без изменений. Когда Smarty встречает тэги, то пытается интерпретировать их и вывести вместо них соответствующий результат.
Пред. | Начало | След. |
Smarty для дизайнеров шаблонов | Уровень выше | Функции |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
name | строка (string) | Нет | checkbox | название списка флажков |
values | массив | Да, если не указан аттрибут options | n/a | Массив значений для флажков |
output | массив | Да, если не указан аттрибут options | n/a | массив названий флажков |
checked | строка (string) | Нет | пусто | выбранный флажок |
options | ассоциативный массив | Да, если не указаны аттрибуты values и output | n/a | Ассоциативнй массив значений и названий |
separator | строка (string) | Нет | пусто | строка разделяющая каждый флажок |
Пользовательская функция html_checkboxes генерирует группу HTML фложков по указанной информации. Также заботится об флажках, которые выбраны по умолчанию. параметры vslues и output обязательны, если не указан аттрибут options. Весь вывод совместим с XHTML.
Все параметры, которые не указаны в списке выводятся в виде пар name/value в каждом созданном тэге <input>.
Пример 8-6. html_checkboxes
|
Пред. | Начало | След. |
fetch | Уровень выше | html_image |
В smarty включены несколько встроенных функций. Встроенные функции интегрированы в язык шаблонов. Нельзя создавать пользовательские функции с такими же названиями или как-либо модифицировать встроенные функции..
capture используется для того, чтобы присвоить вывод шаблона какой-либо переменной вместо его вывода на экран. Любое содержание между {capture name="foo"} и {/capture} сохраняется в переменную, указанную в атрибуте name. Затем его можно использовать в шаблоне с помощью специальной переменной $smarty.capture.foo, где foo - значение, переданное атрибуту name. Если аттрибут name не указан, то используется default. Каждая комманда {capture} должна иметь пару {/capture}. capture поддерживает вложение.
Техническое замечание: Smarty 1.4.0 - 1.4.4 помещало захваченный вывод в переменную $return. С версии 1.4.5 поведение было изменено на использование атрибута name, так что обновите ваши шаблоны соответственно.
Предостережение |
Будте осторожны, сохраняя вывод комманды insert. Если вы используете кэширование и встречаются команды insert в области кэiированния, то не сохраняйте данный вывод. |
Пред. | Начало | След. |
Комбинирование модификаторов | Уровень выше | config_load |
Можно применять любой количество модификаторов к переменной. Они будут применять в порядке их упоминания слева направо. Модификаторы должны быть разделены символом | (вертикальная черта).
Пример 6-1. комбинирование модификаторов
|
Пред. | Начало | След. |
wordwrap | Уровень выше | Встроенные функции |
Для использования переменных, полученных из файлов конфигураии, необходимо заключить их имя между знаками # или через переменную $smarty.config. Для употребления их в качестве внедренныых переменных можно использовать только второй способ.
Пример 4-5. Переменные из файлов конфигурации
|
Переменные из файлов конфигурации не могут быть использованы, пока они не будут загружены. Эта процедура описана далее в данном руководстве (config_load).
Пред. | Начало | След. |
Переменные | Уровень выше | Зарезервированная переменная {$smarty} |
Smarty поставляется с несколькими пользовательскими функциями, которые вы можете использовать в шаблонах.
Пред. | Начало | След. |
strip | Уровень выше | counter |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
file | строка (string) | Да | n/a | Имя config файла для загрузки |
section | строка (string) | Нет | n/a | Имя секции для загрузки |
scope | строка (string) | Нет | local | Способ обработки области видимости загруженных переменных. Должен быть одинм из local, parent или global. local означает, что переменные загружены в контекст локального шаблона. parent означает, что переменные загружены в контекст как локального, так и родительского шаблона. global означает, что переменные доступны из любого шаблона. |
global | логический (boolean) | Нет | No | Доступны ли переменные из родительского шаблона. Аналогичен scope=parent. ЗАМЕЧАНИЕ: Этот аттрибут перекрывается аттрибутом scope, но все еще поддерживается. Если scope указан, то это значение игнорируется. |
Эта функция используется для загрузки переменных в шаблон из файлов конфигруации. Смотри Файлы конфигурации для дополнительной информации.
Пример 7-2. функция config_load
|
Файлы конфигурации также могут содержать секции. Можно загрузить переменные из определенной секции, указав аттрибут section .
Замечание: Секции файлов конфигурации и встроенная функция section не имеют ничего общего, кроме схожего названия.
Пример 7-3. функция config_load с указанием секции
|
Пред. | Начало | След. |
Встроенные функции | Уровень выше | foreach,foreachelse |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
name | строка (string) | Нет | default | Имя счетчика |
start | number | Нет | 1 | Начальное значение счетчика |
skip | number | Нет | 1 | Шаг счетчика |
direction | строка (string) | Нет | up | Направление (вверх - up/вниз - down) |
логический (boolean) | Нет | true | выводить значение счетчика или нет | |
assign | строка (string) | Нет | n/a | Имя переменной, которой будет присвоен вывод |
counter используется для управления счетчиком. counter запоминает количество итераций. Можно регулировать начало, интервал и направление отсчета, а также указать, выводить ил значение счетчика или нет. Можно запустить несколько счетчиков одновременно, указав уникальное имя для каждого. Если имя счетчика не указано, будет использовано по умолчанию 'default'.
Если указан аттрибут "assign", то вывод тэга counter будет присвоен переменной шаблона, вместо отображения.
Пред. | Начало | След. |
Пользовательские Функции | Уровень выше | cycle |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
name | строка (string) | Нет | default | Название цикла |
values | mixed | Да | N/A | Значения, по которым будет производиться цикл. Либо список, разделеный запятыми (либо другим указанным разделителем), либо массив значений. |
логический (boolean) | Нет | true | Выводить значение, или нет | |
advance | логический (boolean) | Нет | true | Переключаться или нет на следующее значение |
delimiter | строка (string) | Нет | , | Разделитель, используемый в аттрибуте values. |
assign | строка (string) | Нет | n/a | Имя переменной, которой будет присвоен вывод тэга |
Cycle используется для прохода через множество значений. С его помощью можно легко реализовать переключение между двумя и более цветами в таблице, или пройти цикл через массив.
Можно проходить через несколько множеств значений одновременно, указав аттрибут name. Имена должны быть уникальными.
Можно не отображать данный элемент, установив аттрибут print в ложь (false). Удобно для пропуска значения, без его вывода.
Аттрибут advance используется для повтора значения. Если установлен в истина (true), то при следующем вызове cycle будет выведено то же значение.
Если указан специальный аттрибут "assign", то вывод cycle присваивается переменной, вместо отображения.
Пред. | Начало | След. |
counter | Уровень выше | debug |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
output | строка (string) | Нет | html | Тип вывода (html или javascript) |
{debug} выводит консоль отладки. Это работает независимо от значения опции debug. Так как этот тэг обрабатывается в процесе выполнения, то возможно вывести только присвоенные переменные, но не используемые шаблоны. Но вы видите все переменные, доступные в области видимости текущего шаблона.
Пред. | Начало | След. |
cycle | Уровень выше | eval |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
var | mixed | Да | n/a | Переменная (или строка) для обработки |
assign | строка (string) | Нет | n/a | Имя переменной, которой будет присвоен вывод |
eval используется для обработки переменной, как шаблона. Можно использовать для таких вещей, как хранение шаблонных тэгов/переменных в переменной или в файлах конфигруации.
Если указан специальный аттрибут "assign", то вывод тэга eval присваивается переменной, вместо отображения.
Техническое Замечание: Переменные шаблоны обрабатываются так же, как и обычные шаблоны. Они подвластны тем же правилам и ограничениям безопасности.
Техническое Замечание: Переменные шаблоны компилируются при каждоv обращении. Откомпилированные версии не сохраняются! Однако, если кэширование включено, то вывод будет закэширован с остальной частью шаблона.
Пример 8-4. eval
|
Пред. | Начало | След. |
debug | Уровень выше | fetch |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
file | строка (string) | Да | n/a | файл, http или ftp сайт для отображния |
assign | строка (string) | Нет | n/a | Имя переменной, которой будет присвоен вывод |
fetch используется для отображения локальных файлов, http или ftp страниц. Есил файл начинается с "http://", то вебстраница будет получена и выведена. Если файл начинается с "ftp://", то файл будет получен с ftp сервера и выведен. Для локальных файлов должен быть указан либо абсолютный путь, либо путь относительно выполняемого php файла.
Если указать специалньый аттрибут "assign", то вывод функции fetch будет присвоен переменной вместо отображения. Добавлено в Smarty версии 1.5.0.
Техническое Замечание: HTTP переадресация не поддерживается. Убедитесь, что указываете завершающие слэши, где это необходимо.
Техническое Замечание: Если включена security и указан файл из локальной файловой системы, то отобразятся лишь файлы, который находятся в указаных безопасных папках ($secure_dir).
Пример 8-5. fetch
|
Пред. | Начало | След. |
eval | Уровень выше | html_checkboxes |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
from | строка (string) | Да | n/a | Имя массива, по которому надо пройтись |
item | строка (string) | Да | n/a | Имя переменной, которая будет выступать в качестве значения текущего елемента |
key | строка (string) | Нет | n/a | Имя переменной, которая будет выступать в качестве ключа текущего елемента |
name | строка (string) | Нет | n/a | Название цикла foreach для доступа к его свойствам |
Циклы foreach являются альтернативой циклам section . Циклы foreach используются для прохождения по одному массиву. Синтаксис foreach намного проще, чем section , но его можно использовать только для одного массива. Тэг foreach должен иметь в пару тэг /foreach . Обязательные параметры - from и item . Название цикла foreach может быть любой последовательностью букв, цифр и знаков подчеркиваний _. Циклы foreach могут быть вложенные, и имена вложенных циклов должны быть уникальные. Переменная from (обычно массив значений) указывает количество итераций цикла. foreachelse выполняется, если нету значений в переменной from .
Пример 7-5. foreach key
|
Циклы foreach имеют свои свойства, доступ к которым реализуется через {$smarty.foreach.foreachname.varname}, где foreachname это название цикла (значение аттрибута name ), а varname - имя свойства.
Количество отработанных итераций.
Отсчет начинается с 1 и увеличивается на единицу на каждой итерации.
Пред. | Начало | След. |
config_load | Уровень выше | include |
Пред. | Начало | След. |
Troubleshooting | Уровень выше | Обработка переменных по умлочанию |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
prefix | строка (string) | Нет | Date_ | префикс названий переменных |
time | timestamp/ГГГГ-ММ-ДД | Нет | текущее время в формате unix timestamp или ГГГГ-ММ-ДД | используемое время |
start_year | строка (string) | Нет | текущий год | Начальный год в выпадающем спииске. Либо указывается явно, либо относительно текущего года (+/- N) |
end_year | строка (string) | Нет | аналогично start_year | Конечный год в вырадающем списке. Либо указывается явно, либо относительно текущего года (+/- N) |
display_days | логический (boolean) | Нет | true | выводить ли список дней |
display_months | логический (boolean) | Нет | true | выводить ли список месяцев |
display_years | логический (boolean) | Нет | true | выводить ли список лет |
month_format | строка (string) | Нет | %B | Формат названия месяцев (strftime) |
day_format | строка (string) | Нет | %02d | формат названия дней (sprintf) |
day_value_format | строка (string) | Нет | %d | формат значения дней (sprintf) |
year_as_text | логический (boolean) | Нет | false | Выводить ли значение года текстом |
reverse_years | логический (boolean) | Нет | false | Выводить года в обратном порядке |
field_array | строка (string) | Нет | null | название переменной (name), которая будет содержать выбранные значения в виде массива: name[Day], name[Year], name[Month]. |
day_size | строка (string) | Нет | null | Устанавливает аттрибут size тэга select для дней |
month_size | строка (string) | Нет | null | Устанавливает аттрибут size тэга select для месяцев |
year_size | строка (string) | Нет | null | Устанавливает аттрибут size тэга select для лет |
all_extra | строка (string) | Нет | null | Устанавливает дополнительные аттрибуты для всех тэгов select/input |
day_extra | строка (string) | Нет | null | Устанавливает дополнительные аттрибуты тэгов select/input для дней |
month_extra | строка (string) | Нет | null | Устанавливает дополнительные аттрибуты тэгов select/input для месяцев |
year_extra | строка (string) | Нет | null | Устанавливает дополнительные аттрибуты тэгов select/input для лет |
field_order | строка (string) | Нет | MDY | Порядок следования полей (МДГ) |
field_separator | строка (string) | Нет | \n | текст, раздляющий поля |
month_value_format | строка (string) | Нет | %m | формат значения месяца (strftime). По умолчанию - %m (номер месяца). |
пользовательская функция html_select_date генерирует поля выбора даты.
Пример 8-10. html_select_date
|
Пример 8-11. html_select_date
|
Пред. | Начало | След. |
html_radios | Уровень выше | html_select_time |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
file | строка (string) | Да | n/a | название/путь к изображению |
border | строка (string) | Нет | 0 | размер рамки вокруг изображения |
height | строка (string) | Нет | реальная высота изображения | высота изображения |
width | строка (string) | Нет | реальная ширина изображения | ширина изображения |
basedir | строка (string) | Нет | корень веб сервера | папка, от которой указаны относительные пути |
link | строка (string) | Нет | n/a | значение href, куда ссылается картинка |
Пользовательская функция html_image генерирует HTML для изображения. Ширина и высота автоматически вычисляются из файла изображения, если не указаны явно.
basedir - базовая папка для относительных путей. Если не указана, то используется корень веб сервер (переменная окружени DOCUMENT_ROOT). Если security включено, то путь к изображения должен быть в пределах безопасных папок.
Аттрибут link указывает, куда ссылается изображение. Аттрибут link устанавливает значение аттрибута href тэга А. Если указан аттрибут link, то изображение окружается выражениями <a href="LINKVALUE"> и <a>.
Техническое Замечание: html_image требует обращение к диску lzk чтения изображения и вычисления его размеров. Если не используется кэширование шаблонов, то тогда лушче не пользоваться тэгом html_image и вставлять статические тэги изображений, для достижения оптимального быстродействия.
Пример 8-7. html_image
|
Пред. | Начало | След. |
html_checkboxes | Уровень выше | html_options |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
values | массив | Да, если не указан аттрибут options | n/a | массив значений для выпадающего списка |
output | массив | Да, если не указан аттрибут options | n/a | массив названий для выпадающего списка |
selected | string/array | Нет | пусто | Выбранный элемент(ы) |
options | ассоциативный массив | Да, если не указаны аттрибуты values и output | n/a | ассоциативный массив значений и названий |
name | строка (string) | Нет | пусто | Название выпадающего списка |
пользовательская функция html_options генерирует группу html тэгов option по указанной информации. Также заботится о выбранных по умолчанию элементах. Аттрибуты values и output обязательны, если не указан аттрибут options.
Если данное значение - массив, то оно будет представлено в виде html OPTGROUP. Рекурсия с OPTGROUP поддерживается. Весь вывод совместим с XHTML.
Если указан необязательный аттрибут name , то группа опций заключится в тэг <select name="groupname"> и </select>, иначе сгенерируется только группа опций.
Все параметры, которые не указаны выше, выводятся в виде пары name/value внутри тэга <select>-tag. Они игнорируются, если аттрибут name не указан.
Пример 8-8. html_options
|
Пред. | Начало | След. |
html_image | Уровень выше | html_radios |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
name | строка (string) | Нет | radio | название элементов выбора |
values | массив | Да, если не указан аттрибут options | n/a | массив значений элементов выбора |
output | массив | Да, если не указан аттрибут options | n/a | массив названий элементов выбора |
checked | строка (string) | Нет | пусто | Значение выбранного элемента |
options | ассоциативный массив | Да, если не указаны аттрибуты values и output | n/a | ассоциативный массив значений и названий элементов выбора |
separator | строка (string) | Нет | пусто | текст, разделяющий элементы выбора |
Пользовательсякая функция html_radios генерирует HMTL код группы элементов выбора (radio button group). Автоматически устанавливает выбранное значение, если оно укзано. Требует наличия аттрибутов values и output или аттрибута options. Сгенерированный HMTL код совместим с XHTML.
Все параметры, которые не указаны в таблице выше, передаются и выводятся внутри каждого созданного тэга <input>.
Пример 8-9. html_radios
|
Пред. | Начало | След. |
html_options | Уровень выше | html_select_date |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
prefix | строка (string) | Нет | Time_ | префикс названий переменных |
time | timestamp | Нет | текущее время | используемое время |
display_hours | логический (boolean) | Нет | true | выводить часы |
display_minutes | логический (boolean) | Нет | true | выводить минуты |
display_seconds | логический (boolean) | Нет | true | выводить секунды |
display_meridian | логический (boolean) | Нет | true | выводить меридиан (am/pm) |
use_24_hours | логический (boolean) | Нет | true | использовать 24-часовой формат времени |
minute_interval | целое (integer) | Нет | 1 | интервал элементов выпадающего списка минут |
second_interval | целое (integer) | Нет | 1 | интервал элементов выпадающего списка секунд |
field_array | строка (string) | Нет | n/a | название переменной, в которую передадутся выбранные значения в виде массива. |
all_extra | строка (string) | Нет | null | указывает дополнительные аттрибуты для всех тэгов select/input |
hour_extra | строка (string) | Нет | null | указывает дополнительные аттрибуты для тэгов select/input для выбора часов |
minute_extra | строка (string) | Нет | null | указывает дополнительные аттрибуты для тэгов select/input для выбора минут |
second_extra | строка (string) | Нет | null | указывает дополнительные аттрибуты для тэгов select/input для выбора секунд |
meridian_extra | строка (string) | Нет | null | указывает дополнительные аттрибуты для тэгов select/input для выбора меридиан |
пользовательская функция html_select_time генерирует HTML поля выбора времени.
Пример 8-12. html_select_time
|
Пред. | Начало | След. |
html_select_date | Уровень выше | html_table |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
loop | массив | Да | n/a | массив данных, по которому будет произведен обход |
cols | целое (integer) | Нет | 3 | количество колонок таблицы |
table_attr | строка (string) | Нет | border="1" | дополнительные аттрибуты тэга table |
tr_attr | строка (string) | Нет | пусто | дополнительные аттрибуты тэга tr (если указан массив, то его элементы циклически повторяються) |
td_attr | строка (string) | Нет | пусто | дополнительные аттрибуты тэга td (если указан массив, то его элементы циклически повторяються) |
trailpad | строка (string) | Нет | | значение остаточных ячеек на последней строке табилцы |
Пользовательская функция html_table выводит массив в виде HTML таблицы. Аттрибут cols указывает количество колонок. Аттрибуты table_attr , tr_attr и td_attr указывают дополнительные аттрибуты тэго table, tr и td. Если значение tr_attr или td_attr - массив, то кго значения циклический повторяются. Атрибут trailpad устанавливает значения для остаточных ячеек на последней строке таблицы.
Пример 8-13. html_table
|
Пред. | Начало | След. |
html_select_time | Уровень выше | math |
Конструкция if в Smarty такая же гибкая, как и аналогичная конструкциия в php, только с несколько расширенными возможностями. with a few added features for the template engine. Каждый тэг 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", "==", "!=", ">", "<", "<=", ">=" -- допустимые квалификаторы условий. Они должны быть отделены от окружающих елементов пробелами.
Пример 7-11. кострукция if
|
Пред. | Начало | След. |
insert | Уровень выше | ldelim,rdelim |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
file | строка (string) | Да | n/a | Имя файла шаблона для включения |
assign | строка (string) | Нет | n/a | Имя переменной, которой присвоится вывод шаблона |
[var ...] | [var type] | Нет | n/a | Переменные, переданные в локальную область включаемого шаблона |
Тэги include используются для включения других шаблонов в текущий. Любые переменные, доступные в текущем шаблоне, доступны и во включаемом. Тэг include должен иметь аттрибут "file", который указывает имя ресурса шаблона.
Опциональный аттрибут assign указывает, что вывод шаблона будет присвоен переменной вместо отображения.
Вы также можете передать переменные в подключаемый шаблон в виде атрибутов. Любая переменная, переданная в подключаемый шаблон, доступны только в области видимости подключаемого файла. Переданные переменные имеют преимущество перед существующими переменными с аналогичными именами.
Для подключения файлов вне папки $template_dir можно указывать файл с помощью ресурсов.
Пример 7-8. функция include: пример использвоания ресурсов
|
Пред. | Начало | След. |
foreach,foreachelse | Уровень выше | include_php |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
file | строка (string) | Да | n/a | Имя подключаемого php файла |
once | логический (boolean) | Нет | true | Укзаывает подключать файл или нет, если он уже был однажды подключен |
assign | строка (string) | Нет | n/a | Название переменной, которой будет присвоен вывод include_php |
Тэг include_php используется для подключения php скрипта в шаблон. Если security включен, то php скрипт должен быть расположен в папке $trusted_dir. Тэг include_php должен иметь атрибут "file", который указывает путь подключаемого php файла (относительный к $trusted_dir или абсолютный путь).
include_php это хороший путь для управления компонентными шаблонами, держать PHP код вне файлов шаблонов. Допустим у вас есть шаблон, который выводит навигацию сайта, информация о которой динамически загружается из базы данных. Вы можете хранить php файл, который получает данные из базы данных, в отдельной папке, и подключать его в начале шаблона. Теперь можно подключать этот файл шаблона в любом месте, не волнуясь о происхождении информации (база данных или нет).
По умолчанию, php файлы подключаются только один раз, даже если вызываются несколько раз в шаблоне. Можно указать, что файл должен быть подключен каждый раз, указав атрибут once . Установив once в ложь (false) указывает, что файл должен быть подключен вне зависимости от того, был ли он подключен раньше.
Можно указать опциональный атрибут assign , который указывает имя переменной, которой будет присвоен вывод include_php вместо отображения.
Объект smarty доступен в подключаемом php файле как $this.
Пример 7-9. функция include_php
|
Пред. | Начало | След. |
include | Уровень выше | insert |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
name | строка (string) | Да | n/a | Имя функции вставки (insert_name) |
assign | строка (string) | Нет | n/a | Имя переменной, которой будет присвоен вывод |
script | строка (string) | Нет | n/a | Bмя php файла, который будет подключен перед вызовом функции вставки |
[var ...] | [var type] | Нет | n/a | Переменные, передаваемые в функцию вставки |
Тэг insert очень похож на тэг include, кроме случая, когда кэширование включено. Insert тэг не кешируется. Он будет выполнен каждый раз, при обращении к шаблону.
Допустим вы имеете шаблон с баннером вверху страницы. Баннер может содержать любую смесь HTML, исзображенй, flash и т.д., то есть нельзя использовать просто статическую ссылку, и мы не хотим, чтобы код баннера кэшировался с остальной страницей. Тогда используем тэг insert: шаблон знает значения #banner_location_id# и #site_id# (взяты из файла конфигурации) и должен вызвать функцию, чтобы получить код баннера.
В этом примере мы используем имя "getBanner" и передаем параметры #banner_location_id# и #site_id#. Smarty попробует вызывать функцию insert_getBanner() в вашей PHP программе, передав значения #banner_location_id# и #site_id# первым параметром в виде ассоциативного массива. Все имена функций вставки должны начинаться с "insert_" для предотвращения возможных конфликтов имен. Функция insert_getBanner() должна обработать переданные переменные и вернуть результат. Он будет отображен в шаблоне вместо тэга insert. В данном случае Smarty вызовет функцию insert_getBanner(array("lid" => "12345","sid" => "67890")); и выведет результат на месте тэга insert.
Если указан аттрибут "assign", то вывод функции вставки будет присвоен указанной переменной вместо отображения. ЗАМЕЧАНИЕ: присвоение вывода тэга insert переменной шаблона не очень полезно, когда кеширование включено.
Если указан аттрибут "script", то указанный php файл будет подключен (только однажды) перед вызовом функции вставки. Это удобно, когда функция может не сущетсвовать, и должен быть подключен php файл, чтобы определить функцию. Путь к файлу должен быть либо абслотныю, либо относительным относительно $trusted_dir. Когда security активирована, то php файл должен быть в папке $trusted_dir.
Обьект Smarty передается в функцию как второй параметр. Так вы можете использовать и модифицировать информацию из объекта Smarty в функциях вставки.
Техническое Замечание: Некоторые части шаблона можно не кэшировать. Если активировано кэширование, то тэг insert все равно не будет кэширован. Он будет вызван каждый раз при генерации страницы, даже из кешированных страниц. Это полезно для таких вещей, как баннеры, опросы, прогнозы погоды, результаты поиска, области обратной связи и т.д.
Пред. | Начало | След. |
include_php | Уровень выше | if,elseif,else |
ldelim и rdelim используются для отображения разделителей. В нашем случае это "{" и "}". Smarty всегда пытаеться интерпретировать разделители, то есть это это единственный способ вывнсти их.
Пред. | Начало | След. |
if,elseif,else | Уровень выше | literal |
Тэг Literal позволяет указать блок данных, который не должен быть обработан Smarty. Это удобно для вывода javascript кода, когда символы { и } могут быть не правильно поняты парсером шаблонов. Все, что окружено тэгами {literal} и {/literal} не обрабатывается и просто отображается как есть.
Пред. | Начало | След. |
ldelim,rdelim | Уровень выше | php |
Пред. | Начало | След. |
Модификаторы переменных | Уровень выше | cat |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
address | строка (string) | Да | n/a | адрес e-mail |
text | строка (string) | Нет | n/a | название ссылки. По умолчанию: адрес e-mail |
encode | строка (string) | Нет | none | Способ кодирования e-mail. Может быть одним из none, hex или javascript. |
cc | строка (string) | Нет | n/a | адреса e-mail для точной копии. Адреса разделяются запятыми. |
bcc | строка (string) | Нет | n/a | адреса e-mail для "слепой" копии. Адреса разделяются запятыми. |
subject | строка (string) | Нет | n/a | тема письма. |
newsgroups | строка (string) | Нет | n/a | в какие конференции передовать. конференции разделяются запятыми. |
followupto | строка (string) | Нет | n/a | addresses to follow up to. Адреса разделяются запятыми. |
extra | строка (string) | Нет | n/a | Дополнительный аттрибуты, передаваемые в ссылку такие как стили (style) |
пользовательская функция mailto автоматизирует создание ссылок на e-mail адреса с возможностью кодирования их. Кодирование усложняет работу web-пауков, которые собирают e-mail адреса с вашего сайта.
Техническое Замечание: javascript - скорее всего наиболее полная форма кодирования, хотя вы так же можете использовать шестнадцатиричное кодирование.
Пример 8-15. mailto
|
Пред. | Начало | След. |
math | Уровень выше | popup_init |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
equation | строка (string) | Да | n/a | математической выражение |
format | строка (string) | Нет | n/a | формат рузультата (sprintf) |
var | numeric | Да | n/a | переменная выражения |
assign | строка (string) | Нет | n/a | переменная шаблона, которой будет присвоен вывод |
[var ...] | numeric | Да | n/a | дополнительные переменные выражения |
пользовательская функция math позволяет дизайнерам шаблонов вычислять математические выражения в шаблоне. Любая численная переменная шаблона может быть использована в выражении. Переменные, используемые в выражении, передаються в качестве параметров, которые могут быть как и переменные шаблона, так и статические щначения. Допустимые операторы: +, -, /, *, abs, ceil, cos, exp, floor, log, log10, max, min, pi, pow, rand, round, sin, sqrt, srans и tan. Ознакомтесь с php документацией под данным функциям.
Если указан аттрибут "assign", то вывод будет присвоен переменной, вместо отображения.
Техническое Замечание: использование функции math значительно сказывается на времени выполнения программы, так как реализована с помощью php функции eval(). Выполнение математических операций в php программе более эффективно, то есть следует везде, где возможно, делать вычисления в программе и передавать результ в шаблон. Следует также избегать повторяющегося вызова функции math (например в циклах).
Пример 8-14. math
|
Пред. | Начало | След. |
html_table | Уровень выше | mailto |
Тэг php позволяет вставлять php код прямо в шаблон. Он не будет как-либо изменен, независимо от $php_handling настроек. Этот тэг тко для продвинутых пользователей, так как обычно не требуется.
Пред. | Начало | След. |
literal | Уровень выше | section,sectionelse |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
text | строка (string) | Да | n/a | HTML код (текст), который будет выводиться в высплывающем окне. |
trigger | строка (string) | Нет | onMouseOver | Способ вызова окна. Может быть либо onMouseOver, либо onClick |
sticky | логический (boolean) | Нет | false | Makes the popup stick around until closed |
caption | строка (string) | Нет | n/a | устанавливает заголовок |
fgcolor | строка (string) | Нет | n/a | цвет внутри окна |
bgcolor | строка (string) | Нет | n/a | цвет границы окна |
textcolor | строка (string) | Нет | n/a | цвет текста в окне |
capcolor | строка (string) | Нет | n/a | цвет заголовка окна |
closecolor | строка (string) | Нет | n/a | цвет текста текста "Close" (Закрыть) |
textfont | строка (string) | Нет | n/a | шрифт текста в окне |
captionfont | строка (string) | Нет | n/a | шрифт заголовка окна |
closefont | строка (string) | Нет | n/a | шрифт текста "Close" (Закрыть) |
textsize | строка (string) | Нет | n/a | размер шрифта в окне |
captionsize | строка (string) | Нет | n/a | размер шрифта заголовка |
closesize | строка (string) | Нет | n/a | размер шрифта текста "Close" (Закрыть) |
width | целое (integer) | Нет | n/a | ширина окна |
height | целое (integer) | Нет | n/a | высота окна |
left | логический (boolean) | Нет | false | создавать окно слева от курсора мыши |
right | логический (boolean) | Нет | false | создавать окно справа от курсора мыши |
center | логический (boolean) | Нет | false | создавать окно на месте мыши |
above | логический (boolean) | Нет | false | создает окно выше курсора мыши. ЗАМЕЧАНИЕ: возможно только если указан аттрибут height |
below | логический (boolean) | Нет | false | создает окно под курсором мыши |
border | целое (integer) | Нет | n/a | толщина границы окна |
offsetx | целое (integer) | Нет | n/a | горизонтальное смещение окна от курсора мыши. |
offsety | целое (integer) | Нет | n/a | вертикальное смещение окна от курсора мыши |
fgbackground | url to image | Нет | n/a | определяет фоновое изображение текста, вместо fgcolor. |
bgbackground | url to image | Нет | n/a | определяет фоновое изображение для границ окна, вместо bgcolor. ЗАМЕЧАНИЕ: Может понадобиться установить bgcolor в "" или будет показан цвет, а не зиображение. ЗАМЕЧАНИЕ: При наличии ссылки "Close" Netscape перерисовывает ячейки таблицы, что приводит к некоректному отображению. |
closetext | строка (string) | Нет | n/a | устанвливает текст вместо "Close" |
noclose | логический (boolean) | Нет | n/a | не отображать текст "Close" |
status | строка (string) | Нет | n/a | установить значение строки статуса в браузере |
autostatus | логический (boolean) | Нет | n/a | установить значение строки статуса в браузере в текст окна. ЗАМЕЧАНИЕ: отменяет значение status |
autostatuscap | строка (string) | Нет | n/a | установить значение строки статуса в браузере в текст заголовка. ЗАМЕЧАНИЕ: отменяет начение autostatus |
inarray | целое (integer) | Нет | n/a | указывает, что текст окна следует взять из указанного элемента массива ol_text, расположенного в overlib.js. Этот параметр может использоваться вместо text |
caparray | целое (integer) | Нет | n/a | указывает, что заголовок окна следует взять из указанного элемента массива ol_caps |
capicon | url | Нет | n/a | выводит изображение перед заголовком окна. |
snapx | целое (integer) | Нет | n/a | ровняет окно к горизонтальной сетке |
snapy | целое (integer) | Нет | n/a | ровняет окно к вертикальной сетке |
fixx | целое (integer) | Нет | n/a | закрепляет горизонтальное положение окна. Замечание: отменяет все остальные параметры горизонтального положения |
fixy | целое (integer) | Нет | n/a | закрепляет вертикалнное положение окна. Замечание: отменяет все остальные параметры вертикального положения |
background | url | Нет | n/a | указывает фоновое изображение окна |
padx | integer,integer | Нет | n/a | дополняет фоновое изображение горизонтальными отступами к тексту. Обратите внимание: этот параметр принимает два значения |
pady | integer,integer | Нет | n/a | дополняет фоновое изображение вертикальными отступами к тексту. Обратите внимание: этот параметр принимает два значения |
fullhtml | логический (boolean) | Нет | n/a | Позволяет полностью контролировать HMTL над фоновым изображением. HTML код ожидается в параметре text |
frame | строка (string) | Нет | n/a | Контролировать высплывающие окна в различных фрэймах. См. сайт overlib для дополнительной информации по этой функции |
timeout | строка (string) | Нет | n/a | вызывает цказанную javascript функцию и использует результат как текст окна |
delay | целое (integer) | Нет | n/a | врремя жизни окна в милисекундах. Позволяет реализовывать высплываюющие подсказки. |
hauto | логический (boolean) | Нет | n/a | автоматическое опредление горизонтального местоположения окна относительно мыши. |
vauto | логический (boolean) | Нет | n/a | автоматическое опредление вертикального местоположения окна относительно мыши. |
функция popup используеться для генерации javascript кода, который создаст высплывающее окно.
Пример 8-17. popup
|
Пред. | Начало | След. |
popup_init | Уровень выше | textformat |
функция popup реализует интеграцию с библиотекой overLib, которая используется для создания всплывающих окон. Они могут использоваться для вывода контекстно-зависимой информации, такой как контекстная помощь или всплывающие подсказки. Функция popup_init должна быть вызвана один раз в начале страницы, где планируется вызов функции popup. Библиотеку overLib написал Эрик Босрап (Erik Bosrup). Домашняя страница расположена по адресу http://www.bosrup.com/web/overlib/.
Начиная со Smarty версии 2.1.2, библиотека overLib не включается в релиз. Скачайте библиотеку overLib, поместите файл overlib.js в корень документов (DOCUMENT_ROOT) или глубже. При вызове функции popup_init передайте относительный путь к этому файлу в качестве параметра src.
Пред. | Начало | След. |
mailto | Уровень выше | popup |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
name | строка (string) | Да | n/a | Название секции |
loop | [$variable_name] | Да | n/a | Имя переменной цикла, для определения количества итераций цикла. |
start | целое (integer) | Нет | 0 | Индекс позиции, с которой будет начинаться цикл. Если значение отрицательное, то начальная позиция вычисляется от конца массива. Например, если в переменной цикла 7 элементов и значение атрибута start равно -2, то начальный индекс будет 5. Неверные значения (значения, вне массива) автоматически обрезаются до ближайшего верного значения. |
step | целое (integer) | Нет | 1 | Значение шага, которое используется для прохода по массиву. Например, step=2 указывает обход массива по элементам 0,2,4... Если шаг отрицателен, то обход массива будет производится в обратном направлении. |
max | целое (integer) | Нет | 1 | Максимальное количество итераций цикла. |
show | логический (boolean) | Нет | true | Указывает, показывать или нет эту секцию |
Секции используются для обхода массива данных. Все тэги section должны иметь в пару тэг /section . Обязательные параметры: name и loop . Имя секции может быть какой угодно последовательностью букв, цифр и знаков подчеркиваний. Секции могут быть вложенными. Имена вложенных секций должны отличаться друг от друга. Переменная цикла (обычно массив) определяет количество итериций цикла. Когда отображаем переменную цикла, имя секции должно быть указана после имени переменной в квадратных скобках []. Тэг sectionelse выполняется, когда переменная цикла пуста.
Пример 7-16. section loop variable
|
Пример 7-18. вложенные секции
|
Пример 7-19. секции и ассоциативные массивы
|
Секции также имеют свои собственные аттрибуты, которые определяют определенные настройки секции. Они указываются примерно так: {$smarty.section.sectionname.varname}
ЗАМЕЧАНИЕ: Начиная со Smarty версии 1.5.0, синтаксис аттрибутов секций изменился с {%sectionname.varname%} на {$smarty.section.sectionname.varname}. Старый синтаксис пока поддерживается, но вы встретите только новый стиль в примерах данного руководства.
index хранит текущий индекс цикла, начиная с 0 (или значения аттрибута start), и увеличивается на единицу (или на значение аттрибута step).
Техническое Замечание: Если аттрибуты step и start не указаны, то index аналогичен аттрибуту секции iteration, кроме того, что начинается с 0, а не с 1.
index_prev хранит предыдущий индекс цикла. На первой итерации устанавливается в -1.
Пример 7-22. аттрибут секции index_prev
|
index_next хранит следующий индекс цикла. На последней итерации цикла будет иметь значение на единицу больше текущего индекса (или на другое значение, если указан аттрибут step).
Пример 7-23. аттрибут секции index_next
|
iteration хранит текущую итерацию цикла.
ЗАМЕЧАНИЕ: Значение не зависит от аттрибутов start, step и max, в отличии аттрибута index. Итерации также начинаются с 1, а не с 0, как index. rownum является синонимом для iteration.
Пример 7-24. аттрибут секции iteration
|
first имеет значение истина, если текущая итерация цикла - первая.
Пример 7-25. аттрибут секции first
|
last имеет значение истина, если текущая итерация цикла - последняя. one.
Пример 7-26. аттрибут секции last
|
loop хранит последний отработанный индекс цикла. Может быть использован как внутри секции, так и после нее.
Аттрибут show может принимать логические значения (истина или ложь). Если ложь, то цикл foreach не будет отображаться. Если присутствует тэг foreachelse, то он будет отображен.
Пример 7-29. аттрибут секции show
|
total хранит количество всех итераций цикла. Может быть использвован как в секции, так и после нее.
Пример 7-30. аттрибут секции total
|
Пред. | Начало | След. |
php | Уровень выше | strip |
Часто вебдизайнеры сталкиваются с проблемой, что пробелы и переносы строк влияют на отображение HTML в броузере ("фишки" броузера), то есть может понадобится склеить все теги в шаблоне вместе, чтобы получить желаемый результат. Но в результате получается нечитаемый или трудноредактируемый шаблон.
В выводимом тексте, заключенном между тэгами {strip} и {/strip}, удаляются повторные пробелы и переносы строк, перед отображением. Так вы можете сохранив шаблон читаемым не волноваться насчет лишних пробелов.
Техническое Замечание: {strip}{/strip} не влияет на содержимое переменных шаблона. См. модификатор strip.
Пример 7-31. тэг strip
|
Заметьте, что в данном примере все строки начинаются и заканчиваются HTML тэгами. Учтите, что все строки склеиваются вместе. Если есть обычный текст в начале строки, то может не получиться желаемый результат.
Пред. | Начало | След. |
section,sectionelse | Уровень выше | Пользовательские Функции |
Имя аттрибута | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
style | строка (string) | Нет | n/a | предустановленный стиль |
indent | number | Нет | 0 | отступ строки |
indent_first | number | Нет | 0 | отступ первой строки |
indent_char | строка (string) | Нет | (single space) | символ, которым заполняеться отступ строк. |
wrap | number | Нет | 80 | количество символов в строке |
wrap_char | строка (string) | Нет | \n | текст, разделяющий каждую строку |
wrap_cut | логический (boolean) | Нет | false | Переносить текст по символам (то есть точно по указанной длине строки) (true), или по границам слов (false) |
assign | строка (string) | Нет | n/a | переменная шаблона, которой будет присвоен вывод |
функция textformat используеться для форматирования текст, заключенного внтури ее. В основном убирает лишние пробелы и специальные символы, а так же форматирует абзацы, делает отступы, переносит слова.
Можно указывать параметры явно, или использовать предустановленные стили. На данный момент существует только стиль "email".
Пример 8-18. textformat
|
Пред. | Начало | След. |
popup | Уровень выше | Конфигурационные файлы |
Позиция параметра | Тип | Обязателен | cat | Описание |
---|---|---|---|---|
1 | строка (string) | Нет | пусто | Данная строка добавляется к модифицируемому значению. |
Данная строка добавляется к модифицируемому значению.
Пред. | Начало | След. |
count_characters | Уровень выше | count_paragraphs |
Возвращает количество абзацев в строке.
Пример 5-5. count_paragraphs
|
Пред. | Начало | След. |
cat | Уровень выше | count_sentences |
Возвращает количество предложений.
Пример 5-6. count_sentences
|
Пред. | Начало | След. |
count_paragraphs | Уровень выше | count_words |
Обычно даты в Smarty всегда передаются как временные метки, что позволяет проектировщикам шаблонов использовать date_format для полного контроля над форматированием даты и также делает легким сравнение дат там, где это необходимо.
ЗАМЕЧАНИЕ: Начиная с версии Smarty 1.4.0 вы можете передавать дату в виде временной метки Unix (Unix timestamp), временной метки MySQL или в любом другом виде, который подерживается функцией PHP strtotime().
Когда {html_select_date} используется в шаблоне, программистам может понадобиться получить дату виде временной метки. Вот функция, которая поможет это сделать.
Пример 18-5. Преобразование элементов формы ввода даты назад к временной метке
|
Пред. | Начало | След. |
Присвоение переменной заголовка (title) заголовку шаблона. | Уровень выше | WAP/WML |
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.
Technical Note: This method isn't 100% foolproof. A spammer could conceivably program his e-mail collector to decode these values, but not likely.
Пред. | Начало | След. |
Составные шаблоны | Уровень выше | Источники |
Пред. | Начало | След. |
count_sentences | Уровень выше | date_format |
Позиция параметра | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
1 | строка (string) | Нет | %b %e, %Y | Формат вывода даты. |
2 | строка (string) | Нет | n/a | Если модифицируемое значение пусто, то используется это. |
Формирует дату и время по заданному формату strftime(). Даты могут быть в виде unix timestamps, mysql timestamps или в любом другом виде, который поймет strtotime(). Проектировщики шаблонов могут использовать date_format для контроля над форматом выводимых дат. Если дата, переданная модификатору, пуста, то второй параметр используется как дата.
Пример 5-8. date_format
|
Пример 5-9. date_format conversion specifiers
|
Пред. | Начало | След. |
count_words | Уровень выше | default |
Позиция параметра | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
1 | строка (string) | Нет | пусто | Значение по умолчанию для пустой переменной. |
Используется для установки значения по умолчанию для переменной. Если переменная оказывается пустой, то выводиться значение по умолчанию. Модификатор принимает один параметр.
Пред. | Начало | След. |
date_format | Уровень выше | escape |
Позиция параметра | Тип | Обязателен | Возможные значения | По умолчанию | Описание |
---|---|---|---|---|---|
1 | строка (string) | Нет | html,htmlall,url,quotes,hex,hexentity,javascript | html | Формат защиты (escape). |
"Защищает" специальные символы в переменной. Используется для защиты специальных символов html, защиты специальных символов url, защиты одиночных кавычек, конвертации в шестандцатеричный вид (hex), конвертации каждого символа в шестандцатеричное html представление (hexentity), защита специальных символов javascript.
Пример 5-11. escape
|
Пред. | Начало | След. |
default | Уровень выше | indent |
Позиция параметра | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
1 | целое (integer) | Нет | 4 | Количество символов для вставки. |
2 | строка (string) | Нет | (один пробел) | Символ для вставки. |
Вставляет в начало каждой строки заданное количество заданных символов. По умолчанию вставляеться 4 пробела.
Пример 5-12. indent
|
Пред. | Начало | След. |
escape | Уровень выше | lower |
Пред. | Начало | След. |
indent | Уровень выше | nl2br |
Заменяет все переносы строк на тэг <br /> в заданной переменной. Это эквивалент PHP функции nl2br().
Пред. | Начало | След. |
lower | Уровень выше | regex_replace |
Позиция параметра | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
1 | строка (string) | Да | n/a | Регулярное выражение для замены. |
2 | строка (string) | Да | n/a | Строка для замены. |
Выполняется поиск и замена по регулярному выражению в переменнной. Используется синтаксис для функции preg_replace() из руководства по PHP.
Пример 5-15. regex_replace
|
Пред. | Начало | След. |
nl2br | Уровень выше | replace |
Позиция параметра | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
1 | строка (string) | Да | n/a | Строка для поиска. |
2 | строка (string) | Да | n/a | Строка для замены. |
Выполняеться простой поиск и замена строки.
Пример 5-16. replace
|
Пред. | Начало | След. |
regex_replace | Уровень выше | spacify |
Позиция параметра | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
1 | строка (string) | Нет | один пробел | Строка вставялется между каждым символом переменной. |
Spacify позволяет вставить пробел между каждым символом переменной. Можно также указать другой символ (или строку) для вставки
Пример 5-17. spacify
|
Пред. | Начало | След. |
replace | Уровень выше | string_format |
Форматирует строку по указанному формату. Используется синтаксис форматирования PHP функции sprintf.
Пред. | Начало | След. |
spacify | Уровень выше | strip |
Заменяет все повторные пробелы, новые строки и знаки табуляции на одиночный пробел или на заданную строку.
Замечание: Если вы хотите сделать аналогичную операцию над частью текста шаблона, то используйте функцию strip.
Пример 5-19. strip
|
Пред. | Начало | След. |
string_format | Уровень выше | strip_tags |
Вырезает HTML теги, обычно все между < и >.
Пример 5-20. strip_tags
|
Пред. | Начало | След. |
strip | Уровень выше | truncate |
Позиция параметра | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
1 | целое (integer) | Нет | 80 | Количество символов для обрезания to. |
2 | строка (string) | Нет | ... | Текст, который добавляется, если произошло обрезание. |
3 | логический (boolean) | Нет | false | Указывает, надо ли обрезать по границе слова (false) или по символу (true). |
Обрезает переменную по указанной длине (по умолчанию 80). Вторым параметром можно указать текст, который будет добавлен в конец обрезанной строки. По умолчанию truncate будет пытаться вырезать слово, которой лежит на вырезаемой границе, целиком. Можно указать третий параметр true, если надо обрезать строку точно по определенному символу.
Пример 5-21. truncate
|
Пред. | Начало | След. |
strip_tags | Уровень выше | upper |
Заменяет все маленькие буквы на большие.
Пример 5-22. upper
|
Пред. | Начало | След. |
truncate | Уровень выше | wordwrap |
Позиция параметра | Тип | Обязателен | По умолчанию | Описание |
---|---|---|---|---|
1 | целое (integer) | Нет | 80 | Количество столбцов для переноса. |
2 | строка (string) | Нет | \n | Строка, которая вставляется на месте переноса. |
3 | логический (boolean) | Нет | false | Указывает, переносить по солвам (false) или нет (true). |
Переносит строку по количеству столбцов (по умолчанию 80). Можно указать строку, которая будет вставлятся на месте переноса (по умолчанию символ новой строки). По умолчанию wordwrap пытается переносить по словам, но если указать третим параметром true, то переноситься будет по конкретному символу.
Пример 5-23. wordwrap
|
Пред. | Начало | След. |
upper | Уровень выше | Комбинирование модификаторов |
Модификаторы переменных могут быть прмменены к переменным, пользовательским функциям или строкам. Для их применения надо после модифицируемого значения указать символ | (вертикальная черта) и название модификатора. Так же модификаторы могут принимать параметры, которые влияют на их поведение. Эти параметры следуют за названием модификатора и разделяются : (двоеточием).
Пример 5-1. Пример модификатора
|
Если модификатор применяется к переменной-массиву, то он будет применен к каждому элементу массива. Если же требуется применить модификатор к массиву, как к переменной, то необходимо перед именем модификатора указать символ @. Пример: {$articleTitle|@count} выведет количество елементов в массиве $articleTitle.
Первые буквы каждого слова преобразуются в заглавные.
Пример 5-2. capitalize
|
Пред. | Начало | След. |
Зарезервированная переменная {$smarty} | Уровень выше | count_characters |
Большинство функций принимает параметры, которые уточняют или изменяют ее поведение. Параметры в Smarty очень похожи на параметры в HTML. Не обязательно заключать статические значения в кавычки, хотя текст рекомендуется заключать в кавычки. Переменные также могут быть использованы в качестве параметров, и не должны заключаться в кавычки.
Некоторые параметры принимают логические значения (правда или ложь). Они могут быть указаны словами true, on, и yes, или false, off, и no без кавычек.
Пред. | Начало | След. |
Функции | Уровень выше | Внедренные переменные в двойных кавычках |
Каждый тэг Smarty либо выводит значение переменной, либо вызывает некоторую функцию. Для вызова функции надо название функции и ее параметры заключить в разделители, например: {funcname attr1="val" attr2="val"}.
И встроенные, и пользовательские функции используются с одинаковым синтаксисом. Встроенные функции реализованы внутри Smarty и не могут быть изменены или переопределены. Это такие функции, как if, section, strip. Пользовательские функции реализуются через плагины. Они могут быть изменены по вашему желанию, также вы можете написать новые. Примеры пользовательских функций: html_options, html_select_date.
Пред. | Начало | След. |
Базовый синтаксис | Уровень выше | Параметры |
Smarty распознает переменные, если они встречаются в строках, заключенных в двойные кавычки. Распознаются переменные, состоящие из чисел, букв, символов _,[,]. Если надо использовать другие символы для указания переменной (точка или ->), то переменную необходимо заключить в обратные кавычки ``.
Пример 3-4. Синтаксис внедренных переменных
|
Пред. | Начало | След. |
Параметры | Уровень выше | Переменные |
Smarty имеет несколько различных типов переменных. Он зависит от символа, с которого начинается, или в какой заключена переменная.
Переменные в Smarty могут быть отображены или использованы как аргументы функций и модификаторов, внутри выражений условных операторов и т.д. Для вывода значения переменной надо просто указать между разделителями имя переменной.
[ {$Name} {$Contacts[row].Phone} <body bgcolor="{#bgcolor#}"> |
Переменные, установленные в PHP, употребляются со знаком доллар $ перед ним. Переменные, установленные в шаблоне с помощью функции assign употребляются аналогичным образом.
Чтобы использовать переменную из ассоциативного массива, надо указать ключ элемента после знака '.' (точка).
Пример 4-2. доступ к перременным ассоциативного массива
|
Можно использовать переменную из массива по е индексу. Синтаксис аналогичен PHP.
Пример 4-3. доступ к елементу массива по его индексу
|
Пред. | Начало | След. |
Внедренные переменные в двойных кавычках | Уровень выше | Переменные файлов конфигурации |
Зарезервированная переменная {$smarty} используется для доступа к нескольким специальным переменным. Далее следует полный их список.
К переменным из таких массивов, как _GET, _POST, _COOKIES, _SERVER, _ENV и _SESSION, можно обращаться аналогично нижеприведенным примерам.
Пример 4-6. Вывод переменных запроса
|
К текущему timestamp (штам времени) можно обратиться через {$smarty.now}. Оно содержит число секунд с начала так называемой Эпохи (Epoch, 1 января 1970 года) и может быть передано прямо модификатору date_format для вывода текущей даты.
Доступ к выводу, сохраненному с помощью тэгов {capture}..{/capture}, можно получить используя переменную {$smarty}. Смотрите раздел capture для примера.
Переменная {$smarty} может быть использована для получения значений переменных из файлов конфигураций. {$smarty.config.foo} является синонимом для {#foo#}. Смотрите раздел config_load для примера.
Пред. | Начало | След. |
Переменные файлов конфигурации | Уровень выше | Модификаторы переменных |
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}.
Your function implementation is called twice by Smarty: once for the opening tag, and once for the closing tag.
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.
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.
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.
See also: register_block(), unregister_block().
Пример 16-5. block function
|
Пред. | Начало | След. |
Modifiers | Уровень выше | 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.
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.
See also register_compiler_function(), unregister_compiler_function().
Пример 16-6. simple compiler function
This function can be called from the template as:
The resulting PHP code in the compiled template would be something like this:
|
Пред. | Начало | След. |
Block Functions | Уровень выше | Prefilters/Postfilters |
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.
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).
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.
See also: register_function(), unregister_function().
Пример 16-1. function plugin with output
|
which can be used in the template as:
Question: Will we ever have time travel? Answer: {eightball}. |
Пример 16-2. function plugin without output
|
Пред. | Начало | След. |
Writing Plugins | Уровень выше | Modifiers |
Version 2.0 introduced the plugin architecture that is used for almost all the customizable functionality of Smarty. This includes:
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.
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.
There is only one plugins directory (for performance reasons). To install a plugin, simply place it in the directory and Smarty will use it automatically.
Пред. | Начало | След. |
Resources | Уровень выше | Naming Conventions |
Insert plugins are used to implement functions that are invoked by insert tags in the template.
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.
The insert function is supposed to return the result which will be substituted in place of the insert tag in the template.
Пример 16-11. insert plugin
|
Пред. | Начало | След. |
Resources | Уровень выше | Приложения |
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.
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().
Пример 16-3. simple modifier plugin This plugin basically aliases one of the built-in PHP functions. It does not have any additional parameters.
|
Пример 16-4. more complex modifier plugin
|
Пред. | Начало | След. |
Template Functions | Уровень выше | Block Functions |
Plugin files and functions must follow a very specific naming convention in order to be located by Smarty.
The plugin files must be named as follows:
type . name .php
Where type is one of these plugin types:
And name should be a valid identifier (letters, numbers, and underscores only).
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.
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.
Пред. | Начало | След. |
Extending Smarty With Plugins | Уровень выше | Writing Plugins |
Output filter plugins operate on a template's output, after the template is loaded and executed, but before the output is displayed.
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.
Пример 16-9. output filter plugin
|
Пред. | Начало | След. |
Prefilters/Postfilters | Уровень выше | Resources |
Prefilter and postfilter plugins are very similar in concept; where they differ is in the execution -- more precisely the time of their execution.
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.
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.
Пример 16-7. prefilter plugin
|
Пример 16-8. postfilter plugin
|
Пред. | Начало | След. |
Compiler Functions | Уровень выше | Output Filters |
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.
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.
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.
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.
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.
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.
See also register_resource(), unregister_resource().
Пример 16-10. resource plugin
|
Пред. | Начало | След. |
Output Filters | Уровень выше | Inserts |
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.
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:
require_once SMARTY_DIR . 'plugins/function.html_options.php'; |
As a general rule, Smarty object is always passed to the plugins as the last parameter (except for modifiers).
Пред. | Начало | След. |
Naming Conventions | Уровень выше | Template Functions |
Несомненно, один из наиболее часто задаваемых вопросов в списках рассылки по PHP: как отделить код от представления? Несмотря на то, что PHP называют "языком, встраиваемым в HTML", после написания нескольких проектов, где смешаны PHP и HTML, многие понимают, что разделение формы и содержания - Хорошая Вещь [TM]. Кроме того, во многих компаниях должности дизайнера и программиста разделены между собой. Приходится использовать шаблоны.
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.
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.
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?
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: http://smarty.php.net/ Для подписки на новости, надо послать письмо на smarty-general-subscribe@lists.php.net. Архив подписки доступен на http://marc.theaimsgroup.com/?l=smarty&r=1&w=2.
Пред. | Начало | След. |
Obfuscating E-mail Addresses | Уровень выше | Ошибки |
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).
Пример 15-5. example using MySQL as a cache source
|
Пред. | Начало | След. |
Output Filters | Уровень выше | Resources |
Пред. | Начало | След. |
Smarty для программистов | Уровень выше | Variables |
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.
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.
Пример 15-6. using templates from $template_dir
|
Templates outside of the $template_dir require the file: template resource type, followed by the absolute path and name of the template.
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 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.
Пример 15-9. using custom resources
|
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.
Пример 15-10. using the default template handler function
|
Пред. | Начало | След. |
Cache Handler Function | Уровень выше | Extending Smarty With Plugins |
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?
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.
Пример 18-7. componentized template
|
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.
Пример 18-8. componentized template with include_php
|
Пред. | Начало | След. |
WAP/WML | Уровень выше | Obfuscating E-mail Addresses |
Если переменная встречается часто, то использование модификатора default каждый раз можно избежать, используя функцию assign.
Пред. | Начало | След. |
Советы | Уровень выше | Присвоение переменной заголовка (title) заголовку шаблона. |
Если большинство ваших шаблонов имеют похожие верхние и нижние части, то имеет смысл вынести их в отдельные файлы. Но если шапка должна иметь различные заголовки на различных страницах? Смотрите пример ниже.
Пример 18-3. Присвоение переменной заголовка (title) заголовку шаблона.
|
Если выводится главная страница, то заголовок будет "Main Page", если архивы, то заголовк берется из файла конфигурации. Если заголовок будет пустой, то выведется значение по умолчанию "BC News".
Пред. | Начало | След. |
Обработка переменных по умлочанию | Уровень выше | Даты |
WAP/WML шаблоны требуют, чтобы заголовок Content-type был передан вместе с шаблоном. Простейший путь - написать пользовательскую функцию, которая будет выводить заголовки. Так как мы будем пользоваться тэгами insert, то заголовки не будут кэшироваться. Так же ничего не должно выводиться в браузер до шаблона, иначе заголовки могут быть неправильно восприняты.
Пример 18-6. Использование insert для записи WML Content-Type заголовков
|
Пред. | Начало | След. |
Даты | Уровень выше | Составные шаблоны |
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 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.
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.
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.
Пред. | Начало | След. |
Приложения | Уровень выше | Советы |
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:
Пред. | Начало | След. |
$undefined | Уровень выше | $compile_check |
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.
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.
Пред. | Начало | След. |
$caching | Уровень выше | $cache_lifetime |
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_lifetime | Уровень выше | $cache_modified_check |
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.)
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.
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().
Пред. | Начало | След. |
$cache_dir | Уровень выше | $cache_handler_func |
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.
Пред. | Начало | След. |
$cache_handler_func | Уровень выше | $config_overwrite |
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.
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.
Пред. | Начало | След. |
$force_compile | Уровень выше | $cache_dir |
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.
Пред. | Начало | След. |
$autoload_filters | Уровень выше | $force_compile |
$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:
If $php_handling is set to SMARTY_PHP_ALLOW, this is implicitly changed to SMARTY_PHP_PASSTHRU
PHP functions are not allowed in IF statements, except those specified in the $security_settings
templates can only be included from directories listed in the $secure_dir array
local files can only be fetched from directories listed in the $secure_dir array using {fetch}
{php}{/php} tags are not allowed
PHP functions are not allowed as modifiers, except those specified in the $security_settings
Пред. | Начало | След. |
$php_handling | Уровень выше | $secure_dir |
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.
IF_FUNCS - This is an array of the names of permitted PHP functions in IF statements.
INCLUDE_ANY - true/false. If set to true, any template can be included from the file system, regardless of the $secure_dir list.
PHP_TAGS - true/false. If set to true, {php}{/php} tags are permitted in the templates.
MODIFIER_FUNCS - This is an array of the names of permitted PHP functions used as variable modifiers.
Пред. | Начало | След. |
$secure_dir | Уровень выше | $trusted_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.
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.
Пред. | Начало | След. |
Variables | Уровень выше | $config_dir |
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.
Пред. | Начало | След. |
$request_vars_order | Уровень выше | $use_sub_dirs |
Specifies the name of the compiler class that Smarty will use to compile the templates. The default is 'Smarty_Compiler'. For advanced users only.
Пред. | Начало | След. |
$right_delimiter | Уровень выше | $request_vars_order |
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.
Пред. | Начало | След. |
$config_overwrite | Уровень выше | $config_read_hidden |
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.
Technical Note: It is not recommended to put this directory under the web server document root.
Пред. | Начало | След. |
$compile_dir | Уровень выше | $plugins_dir |
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.
Пред. | Начало | След. |
$config_read_hidden | Уровень выше | $default_template_handler_func |
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.
Пред. | Начало | След. |
$cache_modified_check | Уровень выше | $config_booleanize |
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.
Пред. | Начало | След. |
$config_booleanize | Уровень выше | $config_fix_newlines |
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.
Пред. | Начало | След. |
$debugging | Уровень выше | $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.
Пред. | Начало | След. |
$debug_tpl | Уровень выше | $global_assign |
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.
Пред. | Начало | След. |
$plugins_dir | Уровень выше | $debug_tpl |
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}.
Пред. | Начало | След. |
$use_sub_dirs | Уровень выше | Methods |
This function is called when a template cannot be obtained from its resource.
Пред. | Начало | След. |
$config_fix_newlines | Уровень выше | $php_handling |
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.
Пред. | Начало | След. |
$compile_check | Уровень выше | $caching |
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.
Technical Note: Server variables can be accessed through the $smarty variable, such as {$smarty.server.SCRIPT_NAME}. See the section on the $smarty variable.
Пред. | Начало | След. |
$debugging_ctrl | Уровень выше | $undefined |
Пред. | Начало | След. |
$trusted_dir | Уровень выше | $right_delimiter |
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_PASSTHRU - Smarty echos tags as-is.
SMARTY_PHP_QUOTE - Smarty quotes the tags as html entities.
SMARTY_PHP_REMOVE - Smarty removes the tags from the templates.
SMARTY_PHP_ALLOW - Smarty will execute the tags as PHP code.
NOTE: Embedding PHP code into templates is highly discouraged. Use custom functions or modifiers instead.
Пред. | Начало | След. |
$default_template_handler_func | Уровень выше | $security |
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.
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.
Пред. | Начало | След. |
$config_dir | Уровень выше | $debugging |
The order in which request variables are registered, similar to variables_order in php.ini
Пред. | Начало | След. |
$compiler_class | Уровень выше | $compile_id |
Пред. | Начало | След. |
$left_delimiter | Уровень выше | $compiler_class |
This is an array of all local directories that are considered secure. {include} and {fetch} use this when security is enabled.
Пред. | Начало | След. |
$security | Уровень выше | $security_settings |
$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_settings | Уровень выше | $left_delimiter |
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.
Пред. | Начало | След. |
$global_assign | Уровень выше | $autoload_filters |
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.
Пред. | Начало | След. |
$compile_id | Уровень выше | $default_modifiers |
Smarty - шаблонный движок для php. Более определенно, он предоставляет управляемый способ разделения прикладной логики и содержания от представления. Это очень удобно в ситуациях, когда программист и проектировщик шаблона играют различные роли, или в часто - это различные люди. Например, скажем, Вы создаете страницу, которая показывает газетную статью. Название статьи, автор и сама статья - елементы, которые не содржат никакой информации о том, как они будут представлены. Их передают в Smarty в приложении, а проектировщик шаблона редактирует шаблоны и использует комбинацию тэгов HTML и тэгов шаблона, чтобы отформатировать представление этих элементов (таблицы HTML, фоновые цвета, размеры шрифта, стиля, и т.д.). Однажды программист захочет изменить способ хранения статьи (сделать изменения в логике приложения.) Это изменение не затрагивает проектировщика шаблонов. Содержание будет все еще передаваться в шаблон таким же самым способом. Аналогично, если проектировщик шаблона хочет полностью перепроектировать шаблоны, это не потребует никаких изменений к прикладной логике. Поэтому, программист может делать изменения в прикладной логике без потребности изменения шаблонов, а проектировщик шаблона может делать изменения в шаблонах без изменения прикладной логики.
Теперь коротко о том, чего не может Smarty. Он не пытается полностью разделить логику от шаблонов. Нет никакой проблемы с логикой в ваших шаблонах при условии, что это строго логика представление. Совета: держите прикладную логику вне шаблонов, а логику представления вне приложения. Так проще всего сохранить проект управляемым и расширяемым в течение долгого времени.
Один из уникальных аспектов в Smarty - компилирование шаблонов. Это означает, что Smarty читает файлы шаблонов и создает php сценарии из них. Они создаются один раз и потом только выполняються. Поэтому нету необходимости обрабатывать файл шаблона для каждого запроса, и каждый шаблон может пользоваться всеми преимуществами кэшируюших решений php компилятора таких, как Zend Accelerator (http://www.zend.com/) или PHP Accelerator (http://www.php-accelerator.co.uk).
Некоторые возможности Smarty:
Он очень быстр.
Он эффективен, так как PHP обработчик делает грязную работу
Никакой лишней обработки шаблонов, они компилируються только один раз.
Перекомпилируются только те шаблоны, которые именились.
Вы можете создавать пользовательскиефункции and модификаторы, так что язык шаблонов чрезвычайно расширяем.
Настраиваемые разделители тэгов шаблона, то есть вы можете использовать {}, {{}}, <!--{}-->, и т.д..
If/elseif/else/endif конструкции передаются PHP обработчику, так что синтаксис {if ...} выражения может быть настолько простым или комплексным, как вам нравится.
Допустимо неограниченное вложение секций, условий и т.д.
Возможно включать php код прямо в ваш шаблон, хотя это не должно требоваться (не рекомендуется), в силу того, что движок гибко настраиваемый.
Встроеное кэширование
Произвольные источники шаблона
Произвольные функции обработки кэширования
Поддержка плагинов
Пред. | Начало | След. |
Приступая к работе | Уровень выше | Инсталяция |