Версия для печати

Архив документации на OpenNet.ru / Раздел "PHP" (Многостраничная версия)

Smarty - компилирующий обработчик шаблонов

Monte Ohrt <monte@ispi.net>
Andrei Zmievski <andrei@php.net>
Sergei Suslenkov <student@bsuir-fcd.org>

21-05-2004

Оригинал: smarty.php.net


Содержание
Предисловие
I. Приступая к работе
1. Что такое Smarty?
2. Инсталяция
Требования
Базовая инсталяция
Extended Setup
II. Smarty для дизайнеров шаблонов
3. Базовый синтаксис
Комментарии
Функции
Параметры
Внедренные переменные в двойных кавычках
4. Переменные
Переменные, установленные в PHP
Переменные файлов конфигурации
Зарезервированная переменная {$smarty}
5. Модификаторы переменных
capitalize
count_characters
cat
count_paragraphs
count_sentences
count_words
date_format
default
escape
indent
lower
nl2br
regex_replace
replace
spacify
string_format
strip
strip_tags
truncate
upper
wordwrap
6. Комбинирование модификаторов
7. Встроенные функции
capture
config_load
foreach,foreachelse
include
include_php
insert
if,elseif,else
ldelim,rdelim
literal
php
section,sectionelse
strip
8. Пользовательские Функции
assign
counter
cycle
debug
eval
fetch
html_checkboxes
html_image
html_options
html_radios
html_select_date
html_select_time
html_table
math
mailto
popup_init
popup
textformat
9. Конфигурационные файлы
10. Отладочная консоль
III. Smarty для программистов
11. Constants
SMARTY_DIR
12. Variables
$template_dir
$compile_dir
$config_dir
$plugins_dir
$debugging
$debug_tpl
$debugging_ctrl
$global_assign
$undefined
$autoload_filters
$compile_check
$force_compile
$caching
$cache_dir
$cache_lifetime
$cache_handler_func
$cache_modified_check
$config_overwrite
$config_booleanize
$config_read_hidden
$config_fix_newlines
$default_template_handler_func
$php_handling
$security
$secure_dir
$security_settings
$trusted_dir
$left_delimiter
$right_delimiter
$compiler_class
$request_vars_order
$compile_id
$use_sub_dirs
$default_modifiers
13. Methods
append
append_by_ref
assign
assign_by_ref
clear_all_assign
clear_all_cache
clear_assign
clear_cache
clear_compiled_tpl
clear_config
config_load
display
fetch
get_config_vars
get_registered_object
get_template_vars
is_cached
load_filter
register_block
register_compiler_function
register_function
register_modifier
register_object
register_outputfilter
register_postfilter
register_prefilter
register_resource
trigger_error
template_exists
unregister_block
unregister_compiler_function
unregister_function
unregister_modifier
unregister_object
unregister_outputfilter
unregister_postfilter
unregister_prefilter
unregister_resource
14. Caching
Setting Up Caching
Multiple Caches Per Page
Cache Groups
15. Advanced Features
Objects
Prefilters
Postfilters
Output Filters
Cache Handler Function
Resources
16. Extending Smarty With Plugins
How Plugins Work
Naming Conventions
Writing Plugins
Template Functions
Modifiers
Block Functions
Compiler Functions
Prefilters/Postfilters
Output Filters
Resources
Inserts
IV. Приложения
17. Troubleshooting
Smarty/PHP errors
18. Советы
Обработка пустых переменных
Обработка переменных по умлочанию
Присвоение переменной заголовка (title) заголовку шаблона.
Даты
WAP/WML
Составные шаблоны
Obfuscating E-mail Addresses
19. Источники
20. Ошибки

Глава 15. Advanced Features

Содержание
Objects
Prefilters
Postfilters
Output Filters
Cache Handler Function
Resources

Objects

Smarty allows access to PHP objects through the templates. There are two ways to access them. One way is to register objects to the template, then use access them via syntax similar to custom functions. The other way is to assign objects to the templates and access them much like any other assigned variable. The first method has a much nicer template syntax. It is also more secure, as a registered object can be restricted to certain methods or properties. However, a registered object cannot be looped over or assigned in arrays of objects, etc. The method you choose will be determined by your needs, but use the first method whenever possible to keep template syntax to a minimum.

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.

Пример 15-1. using a registered or assigned object

<?php
// the object

class My_Object () {
    function
meth1 ( $params , & $smarty_obj ) {
        return
"this is my meth1" ;
    }
}

$myobj = new My_Object ;
// registering the object (will be by reference)
$smarty -> register_object ( "foobar" , $myobj );
// if we want to restrict access to certain methods or properties, list them
$smarty -> register_object ( "foobar" , $myobj ,array( 'meth1' , 'meth2' , 'prop1' ));
// if you want to use the traditional object parameter format, pass a boolean of false
$smarty -> register_object ( "foobar" , $myobj , null , false );

// We can also assign objects. Assign by ref when possible.
$smarty -> assign_by_ref ( "myobj" , $myobj );

$smarty -> display ( "index.tpl" );
?>

TEMPLATE:

{* access our registered object *}
{foobar->meth1 p1="foo" p2=$bar}

{* you can also assign the output *}
{foobar->meth1 p1="foo" p2=$bar assign="output"}
the output was {$output)

{* access our assigned object *}
{$myobj->meth1("foo",$bar)}

Output Filters

When the template is invoked via display() or fetch(), its output can be sent through one or more output filters. This differs from postfilters because postfilters operate on compiled templates before they are saved to the disk, and output filters operate on the template output when it is executed.

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

&lt;?php
// put this in your application
function protect_email($tpl_output, &$smarty)
{
    $tpl_output =
       preg_replace('!(\S+)@([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,3}|[0-9]{1,3}))!',
                    '$1%40$2', $tpl_output);
    return $tpl_output;
}

// register the outputfilter
$smarty->register_outputfilter("protect_email");
$smarty->display("index.tpl");

// now any occurrence of an email address in the template output will have
// a simple protection against spambots
?&gt;

Postfilters

Template postfilters are PHP functions that your templates are ran through after they are compiled. Postfilters can be either registered or loaded from the plugins directory by using load_filter() function or by setting $autoload_filters variable. Smarty will pass the compiled template code as the first argument, and expect the function to return the result of the processing.

Пример 15-3. using a template postfilter

&lt;?php
// put this in your application
function add_header_comment($tpl_source, &$smarty)
{
    return "&lt;?php echo \"&lt;!-- Created by Smarty! --&gt;\n\" ?&gt;\n".$tpl_source;
}

// register the postfilter
$smarty->register_postfilter("add_header_comment");
$smarty->display("index.tpl");
?&gt;

{* compiled Smarty template index.tpl *}
&lt;!-- Created by Smarty! --&gt;
{* rest of template content... *}

Prefilters

Template prefilters are PHP functions that your templates are ran through before they are compiled. This is good for preprocessing your templates to remove unwanted comments, keeping an eye on what people are putting in their templates, etc. Prefilters can be either registered or loaded from the plugins directory by using load_filter() function or by setting $autoload_filters variable. Smarty will pass the template source code as the first argument, and expect the function to return the resulting template source code.

Пример 15-2. using a template prefilter

<?php
// put this in your application
function remove_dw_comments($tpl_source, &$smarty)
{
    return preg_replace("/&lt;!--#.*--&gt;/U","",$tpl_source);
}

// register the prefilter
$smarty->register_prefilter("remove_dw_comments");
$smarty->display("index.tpl");
?>

{* Smarty template index.tpl *}
&lt;!--# this line will get removed by the prefilter --&gt;

append_by_ref

void append_by_ref (string varname, mixed var)

void append_by_ref (string varname, mixed var, boolean merge)

This is used to append values to the templates by reference. If you append a variable by reference then change its value, the appended value sees the change as well. For objects, append_by_ref() also avoids an in-memory copy of the appended object. See the PHP manual on variable referencing for an in-depth explanation. If you pass the optional third parameter of true, the value will be merged with the current array instead of appended.

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.

Пример 13-2. append_by_ref

// appending name/value pairs
$smarty->append_by_ref("Name",$myname);
$smarty->append_by_ref("Address",$address);

assign_by_ref

void assign_by_ref (string varname, mixed var)

This is used to assign values to the templates by reference instead of making a copy. See the PHP manual on variable referencing for an explanation.

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.

Пример 13-4. assign_by_ref

// passing name/value pairs
$smarty->assign_by_ref("Name",$myname);
$smarty->assign_by_ref("Address",$address);

assign

void assign (mixed var)

void assign (string varname, mixed var)

This is used to assign values to the templates. You can explicitly pass name/value pairs, or associative arrays containing the name/value pairs.

Пример 13-3. assign

// passing name/value pairs
$smarty->assign("Name","Fred");
$smarty->assign("Address",$address);

// passing an associative array
$smarty->assign(array("city" => "Lincoln","state" => "Nebraska"));

clear_all_assign

void clear_all_assign ()

This clears the values of all assigned variables.

Пример 13-5. clear_all_assign

// clear all assigned variables
$smarty->clear_all_assign();

clear_all_cache

void clear_all_cache (int expire time)

This clears the entire template cache. As an optional parameter, you can supply a minimum age in seconds the cache files must be before they will get cleared.

Пример 13-6. clear_all_cache

// clear the entire cache
$smarty->clear_all_cache();

clear_assign

void clear_assign (string var)

This clears the value of an assigned variable. This can be a single value, or an array of values.

Пример 13-7. clear_assign

// clear a single variable
$smarty->clear_assign("Name");

// clear multiple variables
$smarty->clear_assign(array("Name","Address","Zip"));

clear_cache

void clear_cache ( [string template [, string cache id [, string compile id [, int expire time]]]])

This clears the cache for a specific template. If you have multiple caches for this template, you can clear a specific cache by supplying the cache id as the second parameter. You can also pass a compile id as a third parameter. You can "group" templates together so they can be removed as a group. See the caching section for more information. As an optional fourth parameter, you can supply a minimum age in seconds the cache file must be before it will get cleared.

Пример 13-8. clear_cache

// clear the cache for a template
$smarty->clear_cache("index.tpl");

// clear the cache for a particular cache id in an multiple-cache template
$smarty->clear_cache("index.tpl","CACHEID");

clear_compiled_tpl

void clear_compiled_tpl (string tpl_file)

This clears the compiled version of the specified template resource, or all compiled template files if one is not specified. This function is for advanced use only, not normally needed.

Пример 13-9. clear_compiled_tpl

// clear a specific template resource
$smarty->clear_compiled_tpl("index.tpl");

// clear entire compile directory
$smarty->clear_compiled_tpl();

fetch

string fetch ( string template [, string cache_id [, string compile_id]])

This returns the template output instead of displaying it. Supply a valid template resource type and path. As an optional second parameter, you can pass a cache id. See the caching section for more information.

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

include("Smarty.class.php");
$smarty = new Smarty;

$smarty->caching = true;

// only do db calls if cache doesn't exist
if(!$smarty->is_cached("index.tpl"))
{

    // dummy up some data
    $address = "245 N 50th";
    $db_data = array(
	    "City" => "Lincoln",
	    "State" => "Nebraska",
	    "Zip" = > "68502"
	    );

    $smarty->assign("Name","Fred");
    $smarty->assign("Address",$address);
    $smarty->assign($db_data);

}

// capture the output
$output = $smarty->fetch("index.tpl");

// do something with $output here

echo $output;

clear_config

void clear_config ( [string var])

This clears all assigned config variables. If a variable name is supplied, only that variable is cleared.

Пример 13-10. clear_config

// clear all assigned config variables.
$smarty->clear_config();

// clear one variable
$smarty->clear_config('foobar');

config_load

void config_load ( string file [, string section])

This loads config file data and assigns it to the template. This works identical to the template config_load function.

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.

Пример 13-11. config_load

// load config variables and assign them
$smarty->config_load('my.conf');

// load a section
$smarty->config_load('my.conf','foobar');

display

void display ( string template [, string cache_id [, string compile_id]])

This displays the template. Supply a valid template resource type and path. As an optional second parameter, you can pass a cache id. See the caching section for more information.

As an optional third parameter, you can pass a compile id. This is in the event that you want to compile different versions of the same template, such as having separate templates compiled for different languages. Another use for compile_id is when you use more than one $template_dir but only one $compile_dir. Set a separate compile_id for each $template_dir, otherwise templates of the same name will overwrite each other. You can also set the $compile_id variable once instead of passing this to each call to display().

Пример 13-12. display

include("Smarty.class.php");
$smarty = new Smarty;
$smarty->caching = true;

// only do db calls if cache doesn't exist
if(!$smarty->is_cached("index.tpl"))
{

    // dummy up some data
    $address = "245 N 50th";
    $db_data = array(
	    "City" => "Lincoln",
	    "State" => "Nebraska",
	    "Zip" = > "68502"
	    );

    $smarty->assign("Name","Fred");
    $smarty->assign("Address",$address);
    $smarty->assign($db_data);

}

// display the output
$smarty->display("index.tpl");

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

Пример 13-13. function display template resource examples

// absolute filepath
$smarty->display("/usr/local/include/templates/header.tpl");

// absolute filepath (same thing)
$smarty->display("file:/usr/local/include/templates/header.tpl");

// windows absolute filepath (MUST use "file:" prefix)
$smarty->display("file:C:/www/pub/templates/header.tpl");

// include from template resource named "db"
$smarty->display("db:header.tpl");

Глава 13. Methods

Содержание
append
append_by_ref
assign
assign_by_ref
clear_all_assign
clear_all_cache
clear_assign
clear_cache
clear_compiled_tpl
clear_config
config_load
display
fetch
get_config_vars
get_registered_object
get_template_vars
is_cached
load_filter
register_block
register_compiler_function
register_function
register_modifier
register_object
register_outputfilter
register_postfilter
register_prefilter
register_resource
trigger_error
template_exists
unregister_block
unregister_compiler_function
unregister_function
unregister_modifier
unregister_object
unregister_outputfilter
unregister_postfilter
unregister_prefilter
unregister_resource

append

void append (mixed var)

void append (string varname, mixed var)

void append (string varname, mixed var, boolean merge)

This is used to append an element to an assigned array. If you append to a string value, it is converted to an array value and then appended to. You can explicitly pass name/value pairs, or associative arrays containing the name/value pairs. If you pass the optional third parameter of true, the value will be merged with the current array instead of appended.

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.

Пример 13-1. append

// passing name/value pairs
$smarty->append("Name","Fred");
$smarty->append("Address",$address);

// passing an associative array
$smarty->append(array("city" => "Lincoln","state" => "Nebraska"));

get_config_vars

array get_config_vars ( [string varname])

This returns the given loaded config variable value. If no parameter is given, an array of all loaded config variables is returned.

Пример 13-15. get_config_vars

// get loaded config template var 'foo'
$foo = $smarty->get_config_vars('foo');

// get all loaded config template vars
$config_vars = $smarty->get_config_vars();

// take a look at them
print_r($config_vars);

get_registered_object

array get_registered_object (string object_name)

This returns a reference to a registered object. This is useful from within a custom function when you need direct access to a registered object.

Пример 13-16. get_registered_object

function smarty_block_foo($params, &$smarty) {
	if (isset[$params['object']]) {
		// get reference to registered object
   		$obj_ref =& $smarty->&get_registered_object($params['object']);
		// use $obj_ref is now a reference to the object
	}
}

get_template_vars

array get_template_vars ( [string varname])

This returns the given assigned variable value. If no parameter is given, an array of all assigned variables is returned.

Пример 13-17. get_template_vars

// get assigned template var 'foo'
$foo = $smarty->get_template_vars('foo');

// get all assigned template vars
$tpl_vars = $smarty->get_template_vars();

// take a look at them
print_r($tpl_vars);

is_cached

void is_cached (string template, [string cache_id])

This returns true if there is a valid cache for this template. This only works if caching is set to true.

Пример 13-18. is_cached

$smarty->caching = true;

if(!$smarty->is_cached("index.tpl")) {
    // do database calls, assign vars here
}

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

You can also pass a cache id as an optional second parameter in case you want multiple caches for the given template.

Пример 13-19. is_cached with multiple-cache template

$smarty->caching = true;

if(!$smarty->is_cached("index.tpl","FrontPage")) {
    // do database calls, assign vars here
}

$smarty->display("index.tpl","FrontPage");

load_filter

void load_filter (string type, string name)

This function can be used to load a filter plugin. The first argument specifies the type of the filter to load and can be one of the following: 'pre', 'post', or 'output'. The second argument specifies the name of the filter plugin, for example, 'trim'.

Пример 13-20. loading filter plugins

$smarty->load_filter('pre', 'trim'); // load prefilter named 'trim'
$smarty->load_filter('pre', 'datefooter'); // load another prefilter named 'datefooter'
$smarty->load_filter('output', 'compress'); // load output filter named 'compress'

register_block

void register_block (string name, string impl)

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

<?php

/* PHP */
$smarty -> register_block ( "translate" , "do_translation" );

function
do_translation ( $params , $content , & $smarty ) {
    if (
$content ) {
        
$lang = $params [ 'lang' ];
        
// do some translation with $content
        
echo $translation ;
    }
}
?>

{* template *}
{translate lang="br"}
   Hello, world!
{/translate}

register_compiler_function

void register_compiler_function (string name, string impl)

Use this to dynamically register a compiler function plugin. Pass in the compiler function name, followed by the PHP function that implements it.


register_function

void register_function (string name, string impl)

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

$smarty->register_function("date_now", "print_current_date");

function print_current_date ($params) {
    extract($params);
    if(empty($format))
        $format="%b %e, %Y";
    echo strftime($format,time());
}

// now you can use this in Smarty to print the current date: {date_now}
// or, {date_now format="%Y/%m/%d"} to format it.

register_modifier

void register_modifier (string name, string impl)

Use this to dynamically register modifier plugin. Pass in the template modifier name, followed by the PHP function that it implements it.

Пример 13-23. register_modifier

// let's map PHP's stripslashes function to a Smarty modifier.

$smarty->register_modifier("sslash","stripslashes");

// now you can use {$var|sslash} to strip slashes from variables

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_prefilter

void register_prefilter (string function_name)

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_outputfilter

void register_outputfilter (string function_name)

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_postfilter

void register_postfilter (string function_name)

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_resource

void register_resource (string name, array resource_funcs)

Use this to dynamically register a resource plugin with Smarty. Pass in the name of the resource and the array of PHP functions implementing it. See template resources for more information on how to setup a function for fetching templates.

Пример 13-24. register_resource

$smarty->register_resource("db", array("db_get_template",
                                       "db_get_timestamp",
                                       "db_get_secure",
                                       "db_get_trusted"));

template_exists

bool template_exists (string template)

This function checks whether the specified template exists. It can accept either a path to the template on the filesystem or a resource string specifying the template.


trigger_error

void trigger_error (string error_msg, [int level])

This function can be used to output an error message using Smarty. level parameter can be one of the values used for trigger_error() PHP function, i.e. E_USER_NOTICE, E_USER_WARNING, etc. By default it's E_USER_WARNING.


unregister_block

void unregister_block (string name)

Use this to dynamically unregister block function plugin. Pass in the block function name.


unregister_compiler_function

void unregister_compiler_function (string name)

Use this to dynamically unregister a compiler function. Pass in the name of the compiler function.


unregister_function

void unregister_function (string name)

Use this to dynamically unregister template function plugin. Pass in the template function name.

Пример 13-25. unregister_function

// we don't want template designers to have access to system files

$smarty->unregister_function("fetch");

unregister_modifier

void unregister_modifier (string name)

Use this to dynamically unregister modifier plugin. Pass in the template modifier name.

Пример 13-26. unregister_modifier

// we don't want template designers to strip tags from elements

$smarty->unregister_modifier("strip_tags");

unregister_object

void unregister_object (string object_name)

Use this to unregister an object.


unregister_outputfilter

void unregister_outputfilter (string function_name)

Use this to dynamically unregister an output filter.


unregister_postfilter

void unregister_postfilter (string function_name)

Use this to dynamically unregister a postfilter.


Глава 14. Caching

Содержание
Setting Up Caching
Multiple Caches Per Page
Cache Groups

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.

Setting Up Caching

The first thing to do is enable caching. This is done by setting $caching = true (or 1.)

Пример 14-1. enabling caching

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

$smarty->caching = true;

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

With caching enabled, the function call to display('index.tpl') will render the template as usual, but also saves a copy of its output to a file (a cached copy) in the $cache_dir. Upon the next call to display('index.tpl'), the cached copy will be used instead of rendering the template again.

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

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

$smarty->caching = 2; // lifetime is per cache

// set the cache_lifetime for index.tpl to 5 minutes
$smarty->cache_lifetime = 300;
$smarty->display('index.tpl');

// set the cache_lifetime for home.tpl to 1 hour
$smarty->cache_lifetime = 3600;
$smarty->display('home.tpl');

// NOTE: the following $cache_lifetime setting will not work when $caching = 2.
// The cache lifetime for home.tpl has already been set
// to 1 hour, and will no longer respect the value of $cache_lifetime.
// The home.tpl cache will still expire after 1 hour.
$smarty->cache_lifetime = 30; // 30 seconds
$smarty->display('home.tpl');

If $compile_check is enabled, every template file and config file that is involved with the cache file is checked for modification. If any of the files have been modified since the cache was generated, the cache is immediately regenerated. This is a slight overhead so for optimum performance, leave $compile_check set to false.

Пример 14-3. enabling $compile_check

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

$smarty->caching = true;
$smarty->compile_check = true;

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

If $force_compile is enabled, the cache files will always be regenerated. This effectively turns off caching. $force_compile is usually for debugging purposes only, a more efficient way of disabling caching is to set $caching = false (or 0.)

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.

Пример 14-4. using is_cached()

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

$smarty->caching = true;

if(!$smarty->is_cached('index.tpl')) {
	// No cache available, do variable assignments here.
	$contents = get_database_contents();
	$smarty->assign($contents);
}

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

You can keep parts of a page dynamic with the insert template function. Let's say the whole page can be cached except for a banner that is displayed down the right side of the page. By using an insert function for the banner, you can keep this element dynamic within the cached content. See the documentation on insert for details and examples.

You can clear all the cache files with the clear_all_cache() function, or individual cache files (or groups) with the clear_cache() function.

Пример 14-5. clearing the cache

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

$smarty->caching = true;

// clear out all cache files
$smarty->clear_all_cache();

// clear only cache for index.tpl
$smarty->clear_cache('index.tpl');

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

Глава 20. Ошибки

Смотрите файл BUGS, который поставляется вместе с стандартной поставко Smarty или ищите список на сайте.


unregister_prefilter

void unregister_prefilter (string function_name)

Use this to dynamically unregister a prefilter.


unregister_resource

void unregister_resource (string name)

Use this to dynamically unregister a resource plugin. Pass in the name of the resource.

Пример 13-27. unregister_resource

$smarty->unregister_resource("db");

Глава 12. Variables

Содержание
$template_dir
$compile_dir
$config_dir
$plugins_dir
$debugging
$debug_tpl
$debugging_ctrl
$global_assign
$undefined
$autoload_filters
$compile_check
$force_compile
$caching
$cache_dir
$cache_lifetime
$cache_handler_func
$cache_modified_check
$config_overwrite
$config_booleanize
$config_read_hidden
$config_fix_newlines
$default_template_handler_func
$php_handling
$security
$secure_dir
$security_settings
$trusted_dir
$left_delimiter
$right_delimiter
$compiler_class
$request_vars_order
$compile_id
$use_sub_dirs
$default_modifiers

$template_dir

This is the name of the default template directory. If you do not supply a resource type when including files, they will be found here. By default this is "./templates", meaning that it will look for the templates directory in the same directory as the executing php script.

Technical Note: It is not recommended to put this directory under the web server document root.


IV. Приложения

Содержание
17. Troubleshooting
18. Советы
19. Источники
20. Ошибки

Cache Groups

You can do more elaborate grouping by setting up cache_id groups. This is accomplished by separating each sub-group with a vertical bar "|" in the cache_id value. You can have as many sub-groups as you like.

Пример 14-9. cache_id groups

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

$smarty->caching = true;

// clear all caches with "sports|basketball" as the first two cache_id groups
$smarty->clear_cache(null,"sports|basketball");

// clear all caches with "sports" as the first cache_id group. This would
// include "sports|basketball", or "sports|(anything)|(anything)|(anything)|..."
$smarty->clear_cache(null,"sports");

$smarty->display('index.tpl',"sports|basketball");

Technical Note: The cache grouping does NOT use the path to the template as any part of the cache_id. For example, if you have display('themes/blue/index.tpl'), you cannot clear the cache for everything under the "themes/blue" directory. If you want to do that, you must group them in the cache_id, such as display('themes/blue/index.tpl','themes|blue'); Then you can clear the caches for the blue theme with clear_cache(null,'themes|blue');


Multiple Caches Per Page

You can have multiple cache files for a single call to display() or fetch(). Let's say that a call to display('index.tpl') may have several different output contents depending on some condition, and you want separate caches for each one. You can do this by passing a cache_id as the second parameter to the function call.

Пример 14-6. passing a cache_id to display()

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

$smarty->caching = true;

$my_cache_id = $_GET['article_id'];

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

Above, we are passing the variable $my_cache_id to display() as the cache_id. For each unique value of $my_cache_id, a separate cache will be generated for index.tpl. In this example, "article_id" was passed in the URL and is used as the cache_id.

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

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

$smarty->caching = true;

$my_cache_id = $_GET['article_id'];

if(!$smarty->is_cached('index.tpl',$my_cache_id)) {
	// No cache available, do variable assignments here.
	$contents = get_database_contents();
	$smarty->assign($contents);
}

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

You can clear all caches for a particular cache_id by passing null as the first parameter to clear_cache().

Пример 14-8. clearing all caches for a particular cache_id

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

$smarty->caching = true;

// clear all caches with "sports" as the cache_id
$smarty->clear_cache(null,"sports");

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

In this manner, you can "group" your caches together by giving them the same cache_id.


Глава 10. Отладочная консоль

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

Замечание: Время загрузки каждого шаблона и файла конфигурации выводятся в секундах или в миллисекундах.


Глава 9. Конфигурационные файлы

С помощью конфигурационных файлов дизайнеру удобно управлять глобальными переменными из одного файлаю. Например, цветами в шаблонах. Обычно, если вы хотите сменить цветувую схему, то необходимо просмотреть каждый шаблон и в каждом изменить цвета. С помощью файла конфигурации все цвета могут быть вынесены в отдельный файл и только один файл надо будет исправлять.

Пример 9-1. Пример файла конфигурации

# глобальные переменные
pageTitle = "Main Menu"
bodyBgColor = #000000
tableBgColor = #000000
rowBgColor = #00ff00

[Customer]
pageTitle = "Customer Info"

[Login]
pageTitle = "Login"
focus = "username"
Intro = """Значение, которое занимает больше
 чем одну строку должно быть заключено
          в тройные кавычки."""

# спрятанная секция
[.Database]
host=my.domain.com
db=ADDRESSBOOK
user=php-user
pass=foobar

Значения переменных могут заключаться в кавычки, но это не обязательно. Можно использовать как двойные, так и одинарные кавычки. Если у вас есть значение, которое занимает больше, чем одну строку, необходимо заключить его в тройные кавычки ("""). Можно включать комментарии в файл конфигурации используя любой синтакис, который не является допустимым синтаксисом файлов конфигурации. Рекомендуется использовать символ # (hash) в начале строки.

Конфигурационный файл в примере имеет две секции. Названия секций заключены в квадратные скобки []. Названия секций могут быть произвольными строками, не содержащими символов [ или ]. Четыре переменные вначале - глобальные переменные или переменные вне секций. Эти переменные всегда загружаются из файла конфигурации. Если загружается определенная секция, то глобальные переменные и переменные из этой секции становятся доступными. Если переменная существует как глобальная, так и внутри секции, то используется версия из секции. Если есть две одинаковые переменные в пределах одной секции, то используеться последний встретившийся вариант.

Файлы конфигурации загружаются в шаблон в помощью функции config_load.

Можно спрятать отдельные переменные или целые секции, добавив к названию точку в начале. Это полезно, когда ваше приложение берет некоторые переменные, ненужные в шаблоне, из файла конфигурации. Если шаблоны могут редактировать третьи лица, то вы можете быть спокойны за ценную информацию из файлов конфигураций: они не смогут ее загрузить в шаблон.


I. Приступая к работе

Содержание
1. Что такое Smarty?
2. Инсталяция

Глава 2. Инсталяция

Содержание
Требования
Базовая инсталяция
Extended Setup

Требования

Smarty необходим вебсервер с запущеным PHP версии 4.0.6 или выше.


Базовая инсталяция

Инсталируйте библиотечный файлы Smarty, которые анаходятся в папке /libs/ дистрибутива. Вы НЕ ДОЛЖНЫ редактировать эти файлы. Они разделены среди всех приложений и могут изменяться только при обновлении Smarty.

Пример 2-1. Бибилотечные файлы Smarty

Smarty.class.php
Smarty_Compiler.class.php
Config_File.class.php
debug.tpl
/plugins/*.php (все файлы!)

Smarty использует PHP константу SMARTY_DIR, которая указывает путь к библиотечным файлам Smarty. Обычно, если приложение может найти файл Smarty.class.php , то нет необходимости устанавливать SMARTY_DIR, Иначе, если Smarty.class.php не в вашем include_path, или вы не указывали абсолютный путь к нему в приложении, то вы должны определить SMARTY_DIR вручную. SMARTY_DIR должен включать завершающий слэш.

Как надо создавать обект Smarty в ваших PHP сценариях:

Пример 2-2. Создание обекта Smarty

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

Попробуйте выполнить вышеупомянутый сценарий. Если Вы получаете ошибку о том, что Smarty.class.php не найден, вы должны селать одно из следующего:

Пример 2-3. Укажите абсолютный путь к библиотечному каталогу

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

Пример 2-4. Добавьте библиотечный каталог к php_include пути

// Отредактируйте ваш php.ini файл, добавьте библиотечный 
// каталог Smarty к include_path и перезаупстите веб сервер.
// Тогда следующее должно работать:
require('Smarty.class.php');
$smarty = new Smarty;

Пример 2-5. Установите SMARTY_DIR константу вручную

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

Теперь, когда библиотечные файлы находятся на месте, пришло время установка каталоги 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

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

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

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

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

Пример 2-7. Setting file permissions

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

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

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

We need to create the index.tpl file that Smarty will load. This will be located in your $template_dir.

Пример 2-8. Editing /web/www.mydomain.com/smarty/guestbook/templates/index.tpl

{* Smarty *}

Hello, {$name}!

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

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

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

$smarty = new Smarty;

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

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

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

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

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

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

// The setup.php file is a good place to load
// required application library files, and you
// can do that right here. An example:
// require('guestbook/guestbook.lib.php');

class Smarty_GuestBook extends Smarty {

   function Smarty_GuestBook() {
   
   		// Class Constructor. These automatically get set with each new instance.

		$this->Smarty();

		$this->template_dir = '/web/www.mydomain.com/smarty/guestbook/templates/';
		$this->compile_dir = '/web/www.mydomain.com/smarty/guestbook/templates_c/';
		$this->config_dir = '/web/www.mydomain.com/smarty/guestbook/configs/';
		$this->cache_dir = '/web/www.mydomain.com/smarty/guestbook/cache/'; 
		
		$this->caching = true;
		$this->assign('app_name','Guest Book');
   }

}

Now lets alter the index.php file to use setup.php:

Пример 2-11. Editing /web/www.mydomain.com/docs/guestbook/index.php

require('guestbook/setup.php');

$smarty = new Smarty_GuestBook;

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

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

Now you see it is quite simple to bring up an instance of Smarty, just use Smarty_GuestBook which automatically initializes everything for our application.


Глава 3. Базовый синтаксис

Содержание
Комментарии
Функции
Параметры
Внедренные переменные в двойных кавычках

Все тэги шаблонов Smarty располагаются между специальными разделителями. По умолчанию это { и }, но они могут быть изменены.

Для наших примеров мы будем использовать стандартные разделители. Smarty все содержимое вне разделителей отображает как статическое содержание, без изменений. Когда Smarty встречает тэги, то пытается интерпретировать их и вывести вместо них соответствующий результат.

Комментарии

Комментарии в шаблонах заключаются в звездочки(*) окруженные . разделителями, например: {* это комментарий *}. Комментарии не отображаются в выводе шаблона. Они используются для внутренних примечаний в шаблонах.

Пример 3-1. Комментарии

{* шаблон Smarty *}

{* подключаем шапку шаблона *}
{include file="header.tpl"}

{include file=$includeFile}

{include file=#includeFile#}

{* выпадающий список *}
<SELECT name=company>
{html_options values=$vals selected=$selected output=$output}
</SELECT>

html_checkboxes

Имя аттрибута Тип Обязателен По умолчанию Описание
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

index.php:

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


 index.tpl:

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


 index.php:

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

 index.tpl:

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


 OUTPUT: (both examples)

 <input type="checkbox" name="id[]" value="1000">Joe Schmoe<br />
 <input type="checkbox" name="id[]" value="1001" checked="checked"><br />
 <input type="checkbox" name="id[]" value="1002">Jane Johnson<br />
 <input type="checkbox" name="id[]" value="1003">Charlie Brown<br />

Глава 7. Встроенные функции

Содержание
capture
config_load
foreach,foreachelse
include
include_php
insert
if,elseif,else
ldelim,rdelim
literal
php
section,sectionelse
strip

В smarty включены несколько встроенных функций. Встроенные функции интегрированы в язык шаблонов. Нельзя создавать пользовательские функции с такими же названиями или как-либо модифицировать встроенные функции..

capture

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ированния, то не сохраняйте данный вывод.

Пример 7-1. Сохранение вывода шаблона

{* we don't want to print a table row unless content is displayed *}
{capture name=banner}
{include file="get_banner.tpl"}
{/capture}
{if $smarty.capture.banner ne ""}
	<tr>
		<td>
			{$smarty.capture.banner}
		</td>
	</tr>
 {/if}


Глава 6. Комбинирование модификаторов

Можно применять любой количество модификаторов к переменной. Они будут применять в порядке их упоминания слева направо. Модификаторы должны быть разделены символом | (вертикальная черта).

Пример 6-1. комбинирование модификаторов

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Smokers are Productive, but Death Cuts Efficiency.');
$smarty->display('index.tpl');

index.tpl:
		 
{$articleTitle}
{$articleTitle|upper|spacify}
{$articleTitle|lower|spacify|truncate}
{$articleTitle|lower|truncate:30|spacify}
{$articleTitle|lower|spacify|truncate:30:". . ."}


OUTPUT:

Smokers are Productive, but Death Cuts Efficiency.
S M O K E R S   A R E   P R O D U C T I V E ,   B U T   D E A T H   C U T S   E F F I C I E N C Y .
s m o k e r s   a r e   p r o d u c t i v e ,   b u t   d e a t h   c u t s...
s m o k e r s   a r e   p r o d u c t i v e ,   b u t . . .
s m o k e r s   a r e   p. . .

Переменные файлов конфигурации

Для использования переменных, полученных из файлов конфигураии, необходимо заключить их имя между знаками # или через переменную $smarty.config. Для употребления их в качестве внедренныых переменных можно использовать только второй способ.

Пример 4-5. Переменные из файлов конфигурации

foo.conf:

pageTitle = "This is mine"
bodyBgColor = "#eeeeee"
tableBorderSize = "3"
tableBgColor = "#bbbbbb"
rowBgColor = "#cccccc"

index.tpl:

{config_load file="foo.conf"}
<html>
<title>{#pageTitle#}</title>
<body bgcolor="{#bodyBgColor#}">
<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">
<tr bgcolor="{#rowBgColor#}">
<td>First</td>
<td>Last</td>
<td>Address</td>
</tr>
</table>
</body>
</html>

index.tpl: (alternate syntax)

{config_load file="foo.conf"}
<html>
<title>{$smarty.config.pageTitle}</title>
<body bgcolor="{$smarty.config.bodyBgColor}">
<table border="{$smarty.config.tableBorderSize}" bgcolor="{$smarty.config.tableBgColor}">
<tr bgcolor="{$smarty.config.rowBgColor}">
<td>First</td>
<td>Last</td>
<td>Address</td>
</tr>
</table>
</body>
</html>


OUTPUT: (same for both examples)

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

Переменные из файлов конфигурации не могут быть использованы, пока они не будут загружены. Эта процедура описана далее в данном руководстве (config_load).


Глава 8. Пользовательские Функции

Содержание
assign
counter
cycle
debug
eval
fetch
html_checkboxes
html_image
html_options
html_radios
html_select_date
html_select_time
html_table
math
mailto
popup_init
popup
textformat

Smarty поставляется с несколькими пользовательскими функциями, которые вы можете использовать в шаблонах.

assign

Имя аттрибута Тип Обязателен По умолчанию Описание
var строка (string) Да n/a Имя переменной, значение которой будет устанавливаться
value строка (string) Да n/a Устанавливаемое значение

assign используется для установки значения переменной в процессе выполнения шаблона.

Пример 8-1. assign

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

Значение $name - {$name}.

OUTPUT:

Значение $name - Bob.

config_load

Имя аттрибута Тип Обязателен По умолчанию Описание
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

{config_load file="colors.conf"}

<html>
<title>{#pageTitle#}</title>
<body bgcolor="{#bodyBgColor#}">
<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">
	<tr bgcolor="{#rowBgColor#}">
		<td>First</td>
		<td>Last</td>
		<td>Address</td>
	</tr>
</table>
</body>
</html>

Файлы конфигурации также могут содержать секции. Можно загрузить переменные из определенной секции, указав аттрибут section .

Замечание: Секции файлов конфигурации и встроенная функция section не имеют ничего общего, кроме схожего названия.

Пример 7-3. функция config_load с указанием секции

{config_load file="colors.conf" section="Customer"}

<html>
<title>{#pageTitle#}</title>
<body bgcolor="{#bodyBgColor#}">
<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">
	<tr bgcolor="{#rowBgColor#}">
		<td>First</td>
		<td>Last</td>
		<td>Address</td>
	</tr>
</table>
</body>
</html>

counter

Имя аттрибута Тип Обязателен По умолчанию Описание
name строка (string) Нет default Имя счетчика
start number Нет 1 Начальное значение счетчика
skip number Нет 1 Шаг счетчика
direction строка (string) Нет up Направление (вверх - up/вниз - down)
print логический (boolean) Нет true выводить значение счетчика или нет
assign строка (string) Нет n/a Имя переменной, которой будет присвоен вывод

counter используется для управления счетчиком. counter запоминает количество итераций. Можно регулировать начало, интервал и направление отсчета, а также указать, выводить ил значение счетчика или нет. Можно запустить несколько счетчиков одновременно, указав уникальное имя для каждого. Если имя счетчика не указано, будет использовано по умолчанию 'default'.

Если указан аттрибут "assign", то вывод тэга counter будет присвоен переменной шаблона, вместо отображения.

Пример 8-2. counter

{* инициализируем счетчик *}
{counter start=0 skip=2 print=false}

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

OUTPUT:

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

cycle

Имя аттрибута Тип Обязателен По умолчанию Описание
name строка (string) Нет default Название цикла
values mixed Да N/A Значения, по которым будет производиться цикл. Либо список, разделеный запятыми (либо другим указанным разделителем), либо массив значений.
print логический (boolean) Нет true Выводить значение, или нет
advance логический (boolean) Нет true Переключаться или нет на следующее значение
delimiter строка (string) Нет , Разделитель, используемый в аттрибуте values.
assign строка (string) Нет n/a Имя переменной, которой будет присвоен вывод тэга

Cycle используется для прохода через множество значений. С его помощью можно легко реализовать переключение между двумя и более цветами в таблице, или пройти цикл через массив.

Можно проходить через несколько множеств значений одновременно, указав аттрибут name. Имена должны быть уникальными.

Можно не отображать данный элемент, установив аттрибут print в ложь (false). Удобно для пропуска значения, без его вывода.

Аттрибут advance используется для повтора значения. Если установлен в истина (true), то при следующем вызове cycle будет выведено то же значение.

Если указан специальный аттрибут "assign", то вывод cycle присваивается переменной, вместо отображения.

Пример 8-3. cycle

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

OUTPUT:

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

debug

Имя аттрибута Тип Обязателен По умолчанию Описание
output строка (string) Нет html Тип вывода (html или javascript)

{debug} выводит консоль отладки. Это работает независимо от значения опции debug. Так как этот тэг обрабатывается в процесе выполнения, то возможно вывести только присвоенные переменные, но не используемые шаблоны. Но вы видите все переменные, доступные в области видимости текущего шаблона.


eval

Имя аттрибута Тип Обязателен По умолчанию Описание
var mixed Да n/a Переменная (или строка) для обработки
assign строка (string) Нет n/a Имя переменной, которой будет присвоен вывод

eval используется для обработки переменной, как шаблона. Можно использовать для таких вещей, как хранение шаблонных тэгов/переменных в переменной или в файлах конфигруации.

Если указан специальный аттрибут "assign", то вывод тэга eval присваивается переменной, вместо отображения.

Техническое Замечание: Переменные шаблоны обрабатываются так же, как и обычные шаблоны. Они подвластны тем же правилам и ограничениям безопасности.

Техническое Замечание: Переменные шаблоны компилируются при каждоv обращении. Откомпилированные версии не сохраняются! Однако, если кэширование включено, то вывод будет закэширован с остальной частью шаблона.

Пример 8-4. eval

setup.conf
----------

emphstart = <b>
emphend = </b>
title = Welcome to {$company}'s home page!
ErrorCity = You must supply a {#emphstart#}city{#emphend#}.
ErrorState = You must supply a {#emphstart#}state{#emphend#}.


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

{config_load file="setup.conf"}

{eval var=$foo}
{eval var=#title#}
{eval var=#ErrorCity#}
{eval var=#ErrorState# assign="state_error"}
{$state_error}

OUTPUT:

This is the contents of foo.
Welcome to Foobar Pub & Grill's home page!
You must supply a <b>city</b>.
You must supply a <b>state</b>.

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

{* включаем javascript в шаблон *}
{fetch file="/export/httpd/www.domain.com/docs/navbar.js"}

{* Добавляем немного прогноза погоды с сервера погоды *}
{fetch file="http://www.myweather.com/68502/"}

{* новостную ленту берем с ftp сервера *}
{fetch file="ftp://user:password@ftp.domain.com/path/to/currentheadlines.txt"}

{* присваиваем полученный файл переменной *}
{fetch file="http://www.myweather.com/68502/" assign="weather"}
{if $weather ne ""}
	&lt;b&gt;{$weather}&lt;/b&gt;
{/if}

foreach,foreachelse

Имя аттрибута Тип Обязателен По умолчанию Описание
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-4. foreach

{* выводятся все значния массива $custid *}
{foreach from=$custid item=curr_id}
	id: {$curr_id}<br>
{/foreach}

OUTPUT:

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

Пример 7-5. foreach key

{* The key contains the key for each looped value

assignment looks like this:

$smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"),
      array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")));

*}

{foreach name=outer item=contact from=$contacts}
  {foreach key=key item=item from=$contact}
    {$key}: {$item}<br>
  {/foreach}
{/foreach}

OUTPUT:

phone: 1<br>
fax: 2<br>
cell: 3<br>
phone: 555-4444<br>
fax: 555-3333<br>
cell: 760-1234<br>

Циклы foreach имеют свои свойства, доступ к которым реализуется через {$smarty.foreach.foreachname.varname}, где foreachname это название цикла (значение аттрибута name ), а varname - имя свойства.

iteration

Количество отработанных итераций.

Отсчет начинается с 1 и увеличивается на единицу на каждой итерации.

first

first устанавливается в true, если текущая итерация первая.

last

last устанавливается в true, если текущая итерация последняя.

show

Аттрибут show может принимать логические значения (истина или ложь). Если ложь, то цикл foreach не будет отображаться. Если присутствует тэг foreachelse, то он будет отображен.

total

total хранит количество итераций цикла. Может быть использовано как в цикле, так и вне его..


Глава 18. Советы

Содержание
Обработка пустых переменных
Обработка переменных по умлочанию
Присвоение переменной заголовка (title) заголовку шаблона.
Даты
WAP/WML
Составные шаблоны
Obfuscating E-mail Addresses

Обработка пустых переменных

Иногда, например, для того чтобы фон таблицы работал корректно, необходимо вывести вместо пустого значения переменной, значение по умолчанию "&nbsp;". Многие бы использовали конструкцию {if}, но есть более короткий путь в Smatry используя default модификатор переменной.

Пример 18-1. Вывод &nbsp;, если переменная пуста

{* длинный путь *}

{if $title eq ""}
 &nbsp;
{else}
	{$title}
{/if}


{* короткий путь *}

{$title|default:"&nbsp;"}

html_select_date

Имя аттрибута Тип Обязателен По умолчанию Описание
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

{html_select_date}


OUTPUT:

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

Пример 8-11. html_select_date

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

OUTPUT: (current year is 2000)

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

html_image

Имя аттрибута Тип Обязателен По умолчанию Описание
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

index.php:

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

index.tpl:

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

OUTPUT: (possible)

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

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

index.php:

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

 index.tpl:

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


 index.php:

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

 index.tpl:

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


 OUTPUT: (both examples)

 <select name=customer_id>
  <option value="1000">Joe Schmoe</option>
  <option value="1001" selected="selected">Jack Smith</option>
  <option value="1002">Jane Johnson</option>
  <option value="1003">Charlie Brown</option>
 </select>

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

index.php:

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


 index.tpl:

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


 index.php:

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


 index.tpl:

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


 OUTPUT: (both examples)

 <input type="radio" name="id[]" value="1000">Joe Schmoe<br />
 <input type="radio" name="id[]" value="1001" checked="checked"><br />
 <input type="radio" name="id[]" value="1002">Jane Johnson<br />
 <input type="radio" name="id[]" value="1003">Charlie Brown<br />

html_select_time

Имя аттрибута Тип Обязателен По умолчанию Описание
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_time use_24_hours=true}


OUTPUT:

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

html_table

Имя аттрибута Тип Обязателен По умолчанию Описание
loop массив Да n/a массив данных, по которому будет произведен обход
cols целое (integer) Нет 3 количество колонок таблицы
table_attr строка (string) Нет border="1" дополнительные аттрибуты тэга table
tr_attr строка (string) Нет пусто дополнительные аттрибуты тэга tr (если указан массив, то его элементы циклически повторяються)
td_attr строка (string) Нет пусто дополнительные аттрибуты тэга td (если указан массив, то его элементы циклически повторяються)
trailpad строка (string) Нет &nbsp; значение остаточных ячеек на последней строке табилцы

Пользовательская функция html_table выводит массив в виде HTML таблицы. Аттрибут cols указывает количество колонок. Аттрибуты table_attr , tr_attr и td_attr указывают дополнительные аттрибуты тэго table, tr и td. Если значение tr_attr или td_attr - массив, то кго значения циклический повторяются. Атрибут trailpad устанавливает значения для остаточных ячеек на последней строке таблицы.

Пример 8-13. html_table

index.php:

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

index.tpl:

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

OUTPUT:

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

if,elseif,else

Конструкция 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

{if $name eq "Fred"}
	Welcome Sir.
{elseif $name eq "Wilma"}
	Welcome Ma'am.
{else}
	Welcome, whatever you are.
{/if}

{* пример с логикой ИЛИ ("or") *}
{if $name eq "Fred" or $name eq "Wilma"}
	...
{/if}

{* аналогичен предыдущему *}
{if $name == "Fred" || $name == "Wilma"}
	...
{/if}

{* следующий синтаксис не будет работать. квалификаторы условий должны 
   быть отделены от окружающих элементов пробелами *}
{if $name=="Fred" || $name=="Wilma"}
	...
{/if}


{* допускаются скобки *}
{if ( $amount < 0 or $amount > 1000 ) and $volume >= #minVolAmt#}
	...
{/if}

{* можно также вызывать встроенные функции php *}
{if count($var) gt 0}
	...
{/if}

{* проверка значения на четность *}
{if $var is even}
	...
{/if}
{if $var is odd}
	...
{/if}
{if $var is not odd}
	...
{/if}

{* проверка на делимость на 4 *}
{if $var is div by 4}
	...
{/if}

{* проверка на "четность" групируя по 2. т.е.,
0=четно, 1=четно, 2=нечетно, 3=нечетно, 4=четно, 5=четно, и т.д. *}
{if $var is even by 2}
	...
{/if}

{* 0=четно, 1=четно, 2=четно, 3=нечетно, 4=нечетно, 5=нечетно, и т.д. *}
{if $var is even by 3}
	...
{/if}

include

Имя аттрибута Тип Обязателен По умолчанию Описание
file строка (string) Да n/a Имя файла шаблона для включения
assign строка (string) Нет n/a Имя переменной, которой присвоится вывод шаблона
[var ...] [var type] Нет n/a Переменные, переданные в локальную область включаемого шаблона

Тэги include используются для включения других шаблонов в текущий. Любые переменные, доступные в текущем шаблоне, доступны и во включаемом. Тэг include должен иметь аттрибут "file", который указывает имя ресурса шаблона.

Опциональный аттрибут assign указывает, что вывод шаблона будет присвоен переменной вместо отображения.

Пример 7-6. функция include

{include file="header.tpl"}

{* тело шаблона *}

{include file="footer.tpl"}

Вы также можете передать переменные в подключаемый шаблон в виде атрибутов. Любая переменная, переданная в подключаемый шаблон, доступны только в области видимости подключаемого файла. Переданные переменные имеют преимущество перед существующими переменными с аналогичными именами.

Пример 7-7. функция include: передача переменных

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

{* тело шаблона *}

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

Для подключения файлов вне папки $template_dir можно указывать файл с помощью ресурсов.

Пример 7-8. функция include: пример использвоания ресурсов

{* абсолютный путь к файлу *}
{include file="/usr/local/include/templates/header.tpl"}

{* абсолютный путь к файлу (аналогично) *}
{include file="file:/usr/local/include/templates/header.tpl"}

{* абсолютный путь к файлу в стиле windows (НЕОБХОДИМО использовать префикс "file:") *}
{include file="file:C:/www/pub/templates/header.tpl"}

{* подключить шаблон из ресурса "db" *}
{include file="db:header.tpl"}

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

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

<?php

	// Загрузка переменных из базы данных mysql и передача их в шаблон
	require_once("MySQL.class.php");
	$sql = new MySQL;
	$sql->query("select * from site_nav_sections order by name",SQL_ALL);
	$this->assign('sections',$sql->record);

?>


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

{* абсолютный путь или относительный относительно $trusted_dir *}
{include_php file="/path/to/load_nav.php"}

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

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# (взяты из файла конфигурации) и должен вызвать функцию, чтобы получить код баннера.

Пример 7-10. функция insert

{* пример установки баннера *}
{insert name="getBanner" lid=#banner_location_id# sid=#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 все равно не будет кэширован. Он будет вызван каждый раз при генерации страницы, даже из кешированных страниц. Это полезно для таких вещей, как баннеры, опросы, прогнозы погоды, результаты поиска, области обратной связи и т.д.


ldelim,rdelim

ldelim и rdelim используются для отображения разделителей. В нашем случае это "{" и "}". Smarty всегда пытаеться интерпретировать разделители, то есть это это единственный способ вывнсти их.

Пример 7-12. ldelim, rdelim

{* будут выведены разделители в шаблона *}

{ldelim}funcname{rdelim} is how functions look in Smarty!


OUTPUT:

{funcname} is how functions look in Smarty!

literal

Тэг Literal позволяет указать блок данных, который не должен быть обработан Smarty. Это удобно для вывода javascript кода, когда символы { и } могут быть не правильно поняты парсером шаблонов. Все, что окружено тэгами {literal} и {/literal} не обрабатывается и просто отображается как есть.

Пример 7-13. тэг literal

{literal}
	<script language=javascript>

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

	</script>
{/literal}

count_characters

Возвращает количество символов в строке.

Пример 5-3. count_characters

index.php:

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

index.tpl:

{$articleTitle}
{$articleTitle|count_characters}

OUTPUT:

Cold Wave Linked to Temperatures.
32

mailto

Имя аттрибута Тип Обязателен По умолчанию Описание
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

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

OUTPUT:

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

math

Имя аттрибута Тип Обязателен По умолчанию Описание
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

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

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

OUTPUT:

9


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

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

OUTPUT:

100


{* можно использовать скобки *}

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

OUTPUT:

6


{* можно указать формат результата (sprintf) *}

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

OUTPUT:

9.44

php

Тэг php позволяет вставлять php код прямо в шаблон. Он не будет как-либо изменен, независимо от $php_handling настроек. Этот тэг тко для продвинутых пользователей, так как обычно не требуется.

Пример 7-14. тэг php

{php}
		// подключение php скрипта прямо
		// из шаблона
		include("/path/to/display_weather.php");
{/php}

popup

Имя аттрибута Тип Обязателен По умолчанию Описание
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 должен быть вызван один раз в начале страницы *}
{popup_init src="/javascripts/overlib.js"}

{* создаем ссылку с всплывающим окном, которое появляеться при наведении мыши *}
<A href="mypage.html" {popup text="This link takes you to my page!"}>mypage</A>

{* можно использовать html, ссылки и т.п. в высплывающем окне *}
<A href="mypage.html" {popup sticky=true caption="mypage contents"
text="<UL><LI>links<LI>pages<LI>images</UL>" snapx=10 snapy=10}>mypage</A>

popup_init

функция 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.

Пример 8-16. popup_init

{* popup_init должен быть вызван один раз в начале страницы *}
 {popup_init src="/javascripts/overlib.js"}

section,sectionelse

Имя аттрибута Тип Обязателен По умолчанию Описание
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-15. section

{* этот пример выведет все значения массива $custid *}
{section name=customer loop=$custid}
	id: {$custid[customer]}<br>
{/section}

OUTPUT:

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

Пример 7-16. section loop variable

{* Переменная цикла определяет только количество итераций цикла.
   Вы имеете доступ к любой переменной шаблона в секции.
   Этот пример подразумевает, что каждый из массивов $custid, $name и $address 
   содержат одинаковое количество значений *}
{section name=customer loop=$custid}
	id: {$custid[customer]}<br>
	name: {$name[customer]}<br>
	address: {$address[customer]}<br>
	<p>
{/section}


OUTPUT:

id: 1000<br>
name: John Smith<br>
address: 253 N 45th<br>
<p>
id: 1001<br>
name: Jack Jones<br>
address: 417 Mulberry ln<br>
<p>
id: 1002<br>
name: Jane Munson<br>
address: 5605 apple st<br>
 <p>

Пример 7-17. имена секций

{* имя секции может быть любым и используется для указания 
   данных в секции *}
{section name=mydata loop=$custid}
	id: {$custid[mydata]}<br>
	name: {$name[mydata]}<br>
	address: {$address[mydata]}<br>
	<p>
{/section}

Пример 7-18. вложенные секции

{* секции могут быть неограничено вложеннымиas. С помощью вложенных секций
   вы можете организовать доступ к комплексным стрктурам информации, таким 
   как многомерные массивы. В данном примере $contact_type[customer] является
   массивом, где содержатся типа контактов данного клиент. *}
{section name=customer loop=$custid}
	id: {$custid[customer]}<br>
	name: {$name[customer]}<br>
	address: {$address[customer]}<br>
	{section name=contact loop=$contact_type[customer]}
		{$contact_type[customer][contact]}: {$contact_info[customer][contact]}<br>
	{/section}
	<p>
{/section}


OUTPUT:

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

Пример 7-19. секции и ассоциативные массивы

{* Пример вывода ассоциативного массива. *}
{section name=customer loop=$contacts}
	name: {$contacts[customer].name}<br>
	home: {$contacts[customer].home}<br>
	cell: {$contacts[customer].cell}<br>
	e-mail: {$contacts[customer].email}<p>
{/section}


OUTPUT:

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

Пример 7-20. sectionelse

{* sectionelse обработается, когда $custid не содержит значений *}
{section name=customer loop=$custid}
	id: {$custid[customer]}<br>
{sectionelse}
	there are no values in $custid.
{/section}

Секции также имеют свои собственные аттрибуты, которые определяют определенные настройки секции. Они указываются примерно так: {$smarty.section.sectionname.varname}

ЗАМЕЧАНИЕ: Начиная со Smarty версии 1.5.0, синтаксис аттрибутов секций изменился с {%sectionname.varname%} на {$smarty.section.sectionname.varname}. Старый синтаксис пока поддерживается, но вы встретите только новый стиль в примерах данного руководства.

index

index хранит текущий индекс цикла, начиная с 0 (или значения аттрибута start), и увеличивается на единицу (или на значение аттрибута step).

Техническое Замечание: Если аттрибуты step и start не указаны, то index аналогичен аттрибуту секции iteration, кроме того, что начинается с 0, а не с 1.

Пример 7-21. аттрибут секции index

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


	OUTPUT:

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

index_prev

index_prev хранит предыдущий индекс цикла. На первой итерации устанавливается в -1.

Пример 7-22. аттрибут секции index_prev

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


	OUTPUT:

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

index_next

index_next хранит следующий индекс цикла. На последней итерации цикла будет иметь значение на единицу больше текущего индекса (или на другое значение, если указан аттрибут step).

Пример 7-23. аттрибут секции index_next

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


	OUTPUT:

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

iteration

iteration хранит текущую итерацию цикла.

ЗАМЕЧАНИЕ: Значение не зависит от аттрибутов start, step и max, в отличии аттрибута index. Итерации также начинаются с 1, а не с 0, как index. rownum является синонимом для iteration.

Пример 7-24. аттрибут секции iteration

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


	OUTPUT:

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

first

first имеет значение истина, если текущая итерация цикла - первая.

Пример 7-25. аттрибут секции first

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

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

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


	OUTPUT:

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

last

last имеет значение истина, если текущая итерация цикла - последняя. one.

Пример 7-26. аттрибут секции last

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

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

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


	OUTPUT:

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

rownum

rownum хранит текущую итерацию цикла, начиная с 1. rownum - синоним для iteration.

Пример 7-27. аттрибут секции rownum

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


	OUTPUT:

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

loop

loop хранит последний отработанный индекс цикла. Может быть использован как внутри секции, так и после нее.

Пример 7-28. аттрбут секции index

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

	There were {$smarty.section.customer.loop} customers shown above.

	OUTPUT:

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

 There were 3 customers shown above.

show

Аттрибут show может принимать логические значения (истина или ложь). Если ложь, то цикл foreach не будет отображаться. Если присутствует тэг foreachelse, то он будет отображен.

Пример 7-29. аттрибут секции show

{* $show_customer_info может быть передана из PHP программы
	укаызвая, показывать или нет эту секцию *}
	{section name=customer loop=$custid show=$show_customer_info}
	{$smarty.section.customer.rownum} id: {$custid[customer]}<br>
	{/section}

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


	OUTPUT:

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

 the section was shown.

total

total хранит количество всех итераций цикла. Может быть использвован как в секции, так и после нее.

Пример 7-30. аттрибут секции total

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

	There were {$smarty.section.customer.total} customers shown above.

	OUTPUT:

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

 There were 3 customers shown above.

strip

Часто вебдизайнеры сталкиваются с проблемой, что пробелы и переносы строк влияют на отображение HTML в броузере ("фишки" броузера), то есть может понадобится склеить все теги в шаблоне вместе, чтобы получить желаемый результат. Но в результате получается нечитаемый или трудноредактируемый шаблон.

В выводимом тексте, заключенном между тэгами {strip} и {/strip}, удаляются повторные пробелы и переносы строк, перед отображением. Так вы можете сохранив шаблон читаемым не волноваться насчет лишних пробелов.

Техническое Замечание: {strip}{/strip} не влияет на содержимое переменных шаблона. См. модификатор strip.

Пример 7-31. тэг strip

{* следующее будет выведено в виде одной строки *}
{strip}
<table border=0>
	<tr>
		<td>
			<A HREF="{$url}">
			<font color="red">This is a test</font>
			</A>
		</td>
	</tr>
</table>
{/strip}


OUTPUT:

<table border=0><tr><td><A HREF="http://my.domain.com"><font color="red">This is a test</font></A></td></tr></table>

Заметьте, что в данном примере все строки начинаются и заканчиваются HTML тэгами. Учтите, что все строки склеиваются вместе. Если есть обычный текст в начале строки, то может не получиться желаемый результат.


textformat

Имя аттрибута Тип Обязателен По умолчанию Описание
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

{textformat wrap=40}

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

This is bar.

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

{/textformat}

OUTPUT:

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

This is bar.

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


{textformat wrap=40 indent=4}

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

This is bar.

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

{/textformat}

OUTPUT:

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

    This is bar.

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

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

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

This is bar.

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

{/textformat}

OUTPUT:

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

        This is bar.

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

{textformat style="email"}

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

This is bar.

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

{/textformat}

OUTPUT:

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

This is bar.

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

cat

Позиция параметра Тип Обязателен cat Описание
1 строка (string) Нет пусто Данная строка добавляется к модифицируемому значению.

Данная строка добавляется к модифицируемому значению.

Пример 5-4. cat

index.php:

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

index.tpl:

{$articleTitle|cat:" yesterday."}

OUTPUT:

Psychics predict world didn't end yesterday.

count_paragraphs

Возвращает количество абзацев в строке.

Пример 5-5. count_paragraphs

index.php:

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

index.tpl:

{$articleTitle}
{$articleTitle|count_paragraphs}

OUTPUT:

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

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

count_sentences

Возвращает количество предложений.

Пример 5-6. count_sentences

index.php:

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

index.tpl:

{$articleTitle}
{$articleTitle|count_sentences}

OUTPUT:

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

Даты

Обычно даты в Smarty всегда передаются как временные метки, что позволяет проектировщикам шаблонов использовать date_format для полного контроля над форматированием даты и также делает легким сравнение дат там, где это необходимо.

ЗАМЕЧАНИЕ: Начиная с версии Smarty 1.4.0 вы можете передавать дату в виде временной метки Unix (Unix timestamp), временной метки MySQL или в любом другом виде, который подерживается функцией PHP strtotime().

Пример 18-4. Использование date_format

{$startDate|date_format}

ВЫВОД:

Jan 4, 2001


{$startDate|date_format:"%Y/%m/%d"}

ВЫВОД:

2001/01/04


{if $date1 < $date2}
	...
{/if}

Когда {html_select_date} используется в шаблоне, программистам может понадобиться получить дату виде временной метки. Вот функция, которая поможет это сделать.

Пример 18-5. Преобразование элементов формы ввода даты назад к временной метке

// Предполагается, что ваши элементы формы названы
// startDate_Day, startDate_Month, startDate_Year

$startDate = makeTimeStamp($startDate_Year,$startDate_Month,$startDate_Day);

function makeTimeStamp($year="",$month="",$day="")
{
	if(empty($year))
		$year = strftime("%Y");
	if(empty($month))
		$month = strftime("%m");
	if(empty($day))
		$day = strftime("%d");

	return mktime(0,0,0,$month,$day,$year);
 }

Obfuscating E-mail Addresses

Do you ever wonder how your E-mail address gets on so many spam mailing lists? One way spammers collect E-mail addresses is from web pages. To help combat this problem, you can make your E-mail address show up in scrambled javascript in the HTML source, yet it it will look and work correctly in the browser. This is done with the mailto plugin.

Пример 18-9. Example of Obfuscating an E-mail Address

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

Send inquiries to
{mailto address=$EmailAddress encode="javascript" subject="Hello"}

Technical Note: This method isn't 100% foolproof. A spammer could conceivably program his e-mail collector to decode these values, but not likely.


count_words

Возвращает количество слов.

Пример 5-7. count_words

index.php:

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

index.tpl:

{$articleTitle}
{$articleTitle|count_words}

OUTPUT:

Dealers Will Hear Car Talk at Noon.
7

date_format

Позиция параметра Тип Обязателен По умолчанию Описание
1 строка (string) Нет %b %e, %Y Формат вывода даты.
2 строка (string) Нет n/a Если модифицируемое значение пусто, то используется это.

Формирует дату и время по заданному формату strftime(). Даты могут быть в виде unix timestamps, mysql timestamps или в любом другом виде, который поймет strtotime(). Проектировщики шаблонов могут использовать date_format для контроля над форматом выводимых дат. Если дата, переданная модификатору, пуста, то второй параметр используется как дата.

Пример 5-8. date_format

index.php:

$smarty = new Smarty;
$smarty->assign('yesterday', strtotime('-1 day'));
$smarty->display('index.tpl');

index.tpl:


{$smarty.now|date_format}
{$smarty.now|date_format:"%A, %B %e, %Y"}
{$smarty.now|date_format:"%H:%M:%S"}
{$yesterday|date_format}
{$yesterday|date_format:"%A, %B %e, %Y"}
{$yesterday|date_format:"%H:%M:%S"}

OUTPUT:

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

Пример 5-9. date_format conversion specifiers

%a - сокращенное название дня недели, в зависимости от текущей локали

%A - полное название дня недели, в зависимости от текущей локали

%b - сокращенное нащвание месяца, в зависимости от текущей локали

%B - полное название месяца, в зависимости от текущей локали

%c - формат даты и времени по умолчанию для текущей локали

%C - номер века (год, деленный на 100, представленный в виде целого в промежутке от 00 до 99) 

%d - день месяца в десятичном формате (от 00 до 31) 

%D - синоним %m/%d/%y 

%e - день месяца в десятичном формате без ведущего нуля (от 1 до 31) 

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

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

%h - синоним %b 

%H - часы по 24-часовым часам (от 00 до 23) 

%I - часы по 12-часовым часам (от 01 до 12) 

%j - день года (от 001 до 366) 

%k - часы по 24-часовым часам без ведущего нуля (от 0 до 23)

%l - часы по 12-часовым часам без ведущего нуля (от 1 до 12)

%m - номер месяца (от 01 до 12) 

%M - минуты

%n - символ новой строки

%p - `am' или `pm', в зависимости от заданного формата времени и текущей локали.

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

%R - time in 24 hour notation 

%S - секунды

%t - символ табуляции

%T - время в формате %H:%M:%S 

%u - номер дня недели [1,7], где 1-ый день - понедельник

%U - номер недели в году, считая первое воскресенья года первым днем первой недели 

%V - номер недели в году (по ISO 8601:1988) в диапазоне от 01 до 53, где первая неделя
	 та, у которой хотя бы 4 дня находяться в данном году. Понедельник считается 
	 первым днем недели. 

%w - номер дня недели, где 0 - воскресенье

%W - номер недели в году, считаю первый понедельник первым днем первой недели.

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

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

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

%Y - year as a decimal number including the century 

%Z - time zone or name or abbreviation 

%% - a literal `%' character 


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

default

Позиция параметра Тип Обязателен По умолчанию Описание
1 строка (string) Нет пусто Значение по умолчанию для пустой переменной.

Используется для установки значения по умолчанию для переменной. Если переменная оказывается пустой, то выводиться значение по умолчанию. Модификатор принимает один параметр.

Пример 5-10. default

index.php:

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

index.tpl:

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

OUTPUT:

Dealers Will Hear Car Talk at Noon.
no title

escape

Позиция параметра Тип Обязателен Возможные значения По умолчанию Описание
1 строка (string) Нет html,htmlall,url,quotes,hex,hexentity,javascript html Формат защиты (escape).

"Защищает" специальные символы в переменной. Используется для защиты специальных символов html, защиты специальных символов url, защиты одиночных кавычек, конвертации в шестандцатеричный вид (hex), конвертации каждого символа в шестандцатеричное html представление (hexentity), защита специальных символов javascript.

Пример 5-11. escape

index.php:

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

index.tpl:

{$articleTitle}
{$articleTitle|escape}
{$articleTitle|escape:"html"}    {* защищает  & " ' < > *}
{$articleTitle|escape:"htmlall"} {* защищает все ВСЕ html объекты *}
{$articleTitle|escape:"url"}
{$articleTitle|escape:"quotes"}
<a
href="mailto:{$EmailAddress|escape:"hex"}">{$EmailAddress|escape:"hexentity"}</a>

OUTPUT:

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

indent

Позиция параметра Тип Обязателен По умолчанию Описание
1 целое (integer) Нет 4 Количество символов для вставки.
2 строка (string) Нет (один пробел) Символ для вставки.

Вставляет в начало каждой строки заданное количество заданных символов. По умолчанию вставляеться 4 пробела.

Пример 5-12. indent

index.php:

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

index.tpl:

{$articleTitle}

{$articleTitle|indent}

{$articleTitle|indent:10}

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

OUTPUT:

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

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

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

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

lower

Все буквы в переменной становятся маленькими.

Пример 5-13. lower

index.php:

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

index.tpl:

{$articleTitle}
{$articleTitle|lower}

OUTPUT:

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

nl2br

Заменяет все переносы строк на тэг <br /> в заданной переменной. Это эквивалент PHP функции nl2br().

Пример 5-14. nl2br

index.php:

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

index.tpl:

{$articleTitle|nl2br}

OUTPUT:

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

regex_replace

Позиция параметра Тип Обязателен По умолчанию Описание
1 строка (string) Да n/a Регулярное выражение для замены.
2 строка (string) Да n/a Строка для замены.

Выполняется поиск и замена по регулярному выражению в переменнной. Используется синтаксис для функции preg_replace() из руководства по PHP.

Пример 5-15. regex_replace

index.php:

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

index.tpl:

{* replace each carriage return, tab & new line with a space *}

{$articleTitle}
{$articleTitle|regex_replace:"/[\r\t\n]/":" "}

OUTPUT:

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

replace

Позиция параметра Тип Обязателен По умолчанию Описание
1 строка (string) Да n/a Строка для поиска.
2 строка (string) Да n/a Строка для замены.

Выполняеться простой поиск и замена строки.

Пример 5-16. replace

index.php:

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

index.tpl:

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

OUTPUT:

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

spacify

Позиция параметра Тип Обязателен По умолчанию Описание
1 строка (string) Нет один пробел Строка вставялется между каждым символом переменной.

Spacify позволяет вставить пробел между каждым символом переменной. Можно также указать другой символ (или строку) для вставки

Пример 5-17. spacify

index.php:

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

index.tpl:

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

OUTPUT:

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

string_format

Позиция параметра Тип Обязателен По умолчанию Описание
1 строка (string) Да n/a Формат. (sprintf)

Форматирует строку по указанному формату. Используется синтаксис форматирования PHP функции sprintf.

Пример 5-18. string_format

index.php:

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

index.tpl:

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

OUTPUT:

23.5787446
23.58
24

strip

Заменяет все повторные пробелы, новые строки и знаки табуляции на одиночный пробел или на заданную строку.

Замечание: Если вы хотите сделать аналогичную операцию над частью текста шаблона, то используйте функцию strip.

Пример 5-19. strip

index.php:

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

index.tpl:

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

OUTPUT:

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

strip_tags

Вырезает HTML теги, обычно все между < и >.

Пример 5-20. strip_tags

index.php:

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

index.tpl:

{$articleTitle}
{$articleTitle|strip_tags}

OUTPUT:

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

truncate

Позиция параметра Тип Обязателен По умолчанию Описание
1 целое (integer) Нет 80 Количество символов для обрезания to.
2 строка (string) Нет ... Текст, который добавляется, если произошло обрезание.
3 логический (boolean) Нет false Указывает, надо ли обрезать по границе слова (false) или по символу (true).

Обрезает переменную по указанной длине (по умолчанию 80). Вторым параметром можно указать текст, который будет добавлен в конец обрезанной строки. По умолчанию truncate будет пытаться вырезать слово, которой лежит на вырезаемой границе, целиком. Можно указать третий параметр true, если надо обрезать строку точно по определенному символу.

Пример 5-21. truncate

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Two Sisters Reunite after Eighteen Years at Checkout Counter.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|truncate}
{$articleTitle|truncate:30}
{$articleTitle|truncate:30:""}
{$articleTitle|truncate:30:"---"}
{$articleTitle|truncate:30:"":true}
{$articleTitle|truncate:30:"...":true}

OUTPUT:

Two Sisters Reunite after Eighteen Years at Checkout Counter.
Two Sisters Reunite after Eighteen Years at Checkout Counter.
Two Sisters Reunite after...
Two Sisters Reunite after
Two Sisters Reunite after---
Two Sisters Reunite after Eigh
Two Sisters Reunite after E...

upper

Заменяет все маленькие буквы на большие.

Пример 5-22. upper

index.php:

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

index.tpl:

{$articleTitle}
{$articleTitle|upper}

OUTPUT:

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

wordwrap

Позиция параметра Тип Обязателен По умолчанию Описание
1 целое (integer) Нет 80 Количество столбцов для переноса.
2 строка (string) Нет \n Строка, которая вставляется на месте переноса.
3 логический (boolean) Нет false Указывает, переносить по солвам (false) или нет (true).

Переносит строку по количеству столбцов (по умолчанию 80). Можно указать строку, которая будет вставлятся на месте переноса (по умолчанию символ новой строки). По умолчанию wordwrap пытается переносить по словам, но если указать третим параметром true, то переноситься будет по конкретному символу.

Пример 5-23. wordwrap

index.php:

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

index.tpl:

{$articleTitle}

{$articleTitle|wordwrap:30}

{$articleTitle|wordwrap:20}

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

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

OUTPUT:

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

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

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

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

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

Глава 5. Модификаторы переменных

Содержание
capitalize
count_characters
cat
count_paragraphs
count_sentences
count_words
date_format
default
escape
indent
lower
nl2br
regex_replace
replace
spacify
string_format
strip
strip_tags
truncate
upper
wordwrap

Модификаторы переменных могут быть прмменены к переменным, пользовательским функциям или строкам. Для их применения надо после модифицируемого значения указать символ | (вертикальная черта) и название модификатора. Так же модификаторы могут принимать параметры, которые влияют на их поведение. Эти параметры следуют за названием модификатора и разделяются : (двоеточием).

Пример 5-1. Пример модификатора

{* Выводим заголовок большими буквами *}
<h2>{$title|upper}</h2>

{* Ограничим $topic 40-а символами и добавим "..." в конце *}
Topic: {$topic|truncate:40:"..."}

{* форматируем строку *}
{"now"|date_format:"%Y/%m/%d"}

{* Применение модификатора к функции *}
{mailto|upper address="me@domain.dom"}

Если модификатор применяется к переменной-массиву, то он будет применен к каждому элементу массива. Если же требуется применить модификатор к массиву, как к переменной, то необходимо перед именем модификатора указать символ @. Пример: {$articleTitle|@count} выведет количество елементов в массиве $articleTitle.

capitalize

Первые буквы каждого слова преобразуются в заглавные.

Пример 5-2. capitalize

index.php:

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

index.tpl:

{$articleTitle}
{$articleTitle|capitalize}

OUTPUT:

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

Параметры

Большинство функций принимает параметры, которые уточняют или изменяют ее поведение. Параметры в Smarty очень похожи на параметры в HTML. Не обязательно заключать статические значения в кавычки, хотя текст рекомендуется заключать в кавычки. Переменные также могут быть использованы в качестве параметров, и не должны заключаться в кавычки.

Некоторые параметры принимают логические значения (правда или ложь). Они могут быть указаны словами true, on, и yes, или false, off, и no без кавычек.

Пример 3-3. Синтаксис параметров функции

{include file="header.tpl"}

{include file=$includeFile}

{include file=#includeFile#}

{html_select_date display_days=yes}

<SELECT name=company>
{html_options values=$vals selected=$selected output=$output}
</SELECT>

Функции

Каждый тэг Smarty либо выводит значение переменной, либо вызывает некоторую функцию. Для вызова функции надо название функции и ее параметры заключить в разделители, например: {funcname attr1="val" attr2="val"}.

Пример 3-2. Синтаксис функций

{config_load file="colors.conf"}

{include file="header.tpl"}

{if $highlight_name}
Welcome, <font color="{#fontColor#}">{$name}!</font>
{else}
Welcome, {$name}!
{/if}

{include file="footer.tpl"}

И встроенные, и пользовательские функции используются с одинаковым синтаксисом. Встроенные функции реализованы внутри Smarty и не могут быть изменены или переопределены. Это такие функции, как if, section, strip. Пользовательские функции реализуются через плагины. Они могут быть изменены по вашему желанию, также вы можете написать новые. Примеры пользовательских функций: html_options, html_select_date.


Внедренные переменные в двойных кавычках

Smarty распознает переменные, если они встречаются в строках, заключенных в двойные кавычки. Распознаются переменные, состоящие из чисел, букв, символов _,[,]. Если надо использовать другие символы для указания переменной (точка или ->), то переменную необходимо заключить в обратные кавычки ``.

Пример 3-4. Синтаксис внедренных переменных

Пример синтаксиса:
{func var="test $foo test"}       <-- ищет $foo
{func var="test $foo_bar test"}   <-- ищет $foo_bar
{func var="test $foo[0] test"}    <-- ищет $foo[0]
{func var="test $foo[bar] test"}  <-- ищет $foo[bar]
{func var="test $foo.bar test"}   <-- ищет $foo (не $foo.bar)
{func var="test `$foo.bar` test"} <-- ищет $foo.bar

Практические примеры:
{include file="subdir/$tpl_name.tpl"} <-- заменит $tpl_name на ее значение
{cycle values="one,two,`$smarty.config.myval`"} <-- надо заключать в обратные кавычки

Глава 4. Переменные

Содержание
Переменные, установленные в PHP
Переменные файлов конфигурации
Зарезервированная переменная {$smarty}

Smarty имеет несколько различных типов переменных. Он зависит от символа, с которого начинается, или в какой заключена переменная.

Переменные в Smarty могут быть отображены или использованы как аргументы функций и модификаторов, внутри выражений условных операторов и т.д. Для вывода значения переменной надо просто указать между разделителями имя переменной.
[
{$Name}

{$Contacts[row].Phone}

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

Переменные, установленные в PHP

Переменные, установленные в PHP, употребляются со знаком доллар $ перед ним. Переменные, установленные в шаблоне с помощью функции assign употребляются аналогичным образом.

Пример 4-1. Установленные переменные

Привет {$firstname}, мы рады снова тебя видеть.
<p>
Последний раз ты посещал нас {$lastLoginDate}.

OUTPUT:

Привет Петя, мы рады снова тебя видеть.
<p>
Последний раз ты посещал нас January 11th, 2001.

Ассоциативные массивы

Чтобы использовать переменную из ассоциативного массива, надо указать ключ элемента после знака '.' (точка).

Пример 4-2. доступ к перременным ассоциативного массива

index.php:

$smarty = new Smarty;
$smarty->assign('Contacts',
  array('fax' => '555-222-9876',
        'email' => 'zaphod@slartibartfast.com',
        'phone' => array('home' => '555-444-3333',
                         'cell' => '555-111-1234')));
$smarty->display('index.tpl');

index.tpl:

{$Contacts.fax}<br>
{$Contacts.email}<br>
{* you can print arrays of arrays as well *}
{$Contacts.phone.home}<br>
{$Contacts.phone.cell}<br>

OUTPUT:

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

Индексированные массивы

Можно использовать переменную из массива по е индексу. Синтаксис аналогичен PHP.

Пример 4-3. доступ к елементу массива по его индексу

index.php:

$smarty = new Smarty;
$smarty->assign('Contacts',
  array('555-222-9876',
        'zaphod@slartibartfast.com',
        array('555-444-3333',
              '555-111-1234')));
$smarty->display('index.tpl');

index.tpl:

{$Contacts[0]}<br>
{$Contacts[1]}<br>
{* you can print arrays of arrays as well *}
{$Contacts[2][0]}<br>
{$Contacts[2][1]}<br>

OUTPUT:

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

Объекты

Чтобы использовать свойства обьектов, надо указать перед именем атрибута знак `->'.

Пример 4-4. доступ к свойствам объекта

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

OUTPUT:

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

Зарезервированная переменная {$smarty}

Зарезервированная переменная {$smarty} используется для доступа к нескольким специальным переменным. Далее следует полный их список.

Переменные запроса.

К переменным из таких массивов, как _GET, _POST, _COOKIES, _SERVER, _ENV и _SESSION, можно обращаться аналогично нижеприведенным примерам.

Пример 4-6. Вывод переменных запроса

{* Вывод значения $page из URL (GET) http://www.domain.com/index.php?page=foo *}
{$smarty.get.page}

{* Вывод переменной "page" из формы (POST) *}
{$smarty.post.page}

{* Вывод значения cookie "username" *}
{$smarty.cookies.username}

{* Вывод переменное сервера "SERVER_NAME" *}
{$smarty.server.SERVER_NAME}

{* Вывод переменной окружения "PATH" *}
{$smarty.env.PATH}

{* Вывод переменной сессии "id" *}
{$smarty.session.id}

{* Вывод переменной "username" из объединенного массива get/post/cookies/server/env *}
{$smarty.request.username}

{$smarty.now}

К текущему timestamp (штам времени) можно обратиться через {$smarty.now}. Оно содержит число секунд с начала так называемой Эпохи (Epoch, 1 января 1970 года) и может быть передано прямо модификатору date_format для вывода текущей даты.

Пример 4-7. использование {$smarty.now}

{* выводим текущее время и дату с помощью модификатора date_format *}
{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}

{$smarty.const}

Реализует доступ к константам PHP.

Пример 4-8. использование {$smarty.const}

{$smarty.const._MY_CONST_VAL}

{$smarty.capture}

Доступ к выводу, сохраненному с помощью тэгов {capture}..{/capture}, можно получить используя переменную {$smarty}. Смотрите раздел capture для примера.

{$smarty.config}

Переменная {$smarty} может быть использована для получения значений переменных из файлов конфигураций. {$smarty.config.foo} является синонимом для {#foo#}. Смотрите раздел config_load для примера.

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

Переменная {$smarty} может быть использована для исппользования свойств структур 'section' и 'foreach'. Смотри разделы по section и foreach.

{$smarty.template}

Эта переменная содержит имя текущего шаблона.


Block Functions

void smarty_block_ name (array $params, mixed $content, object &$smarty)

Block functions are functions of the form: {func} .. {/func}. In other words, they enclose a template block and operate on the contents of this block. Block functions take precedence over custom functions of the same name, that is, you cannot have both custom function {func} and block function {func} .. {/func}.

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

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     block.translate.php
 * Type:     block
 * Name:     translate
 * Purpose:  translate a block of text
 * -------------------------------------------------------------
 */
function smarty_block_translate($params, $content, &$smarty)
{
    if ($content) {
        $lang = $params['lang'];
        // do some intelligent translation thing here with $content
        echo $translation;
    }
}

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.

mixed smarty_compiler_ name (string $tag_arg, object &$smarty)

The compiler function is passed two parameters: the tag argument string - basically, everything from the function name until the ending delimiter, and the Smarty object. It's supposed to return the PHP code to be injected into the compiled template.

See also register_compiler_function(), unregister_compiler_function().

Пример 16-6. simple compiler function

&lt;?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     compiler.tplheader.php
 * Type:     compiler
 * Name:     tplheader
 * Purpose:  Output header containing the source file name and
 *           the time it was compiled.
 * -------------------------------------------------------------
 */
function smarty_compiler_tplheader($tag_arg, &$smarty)
{
    return "\necho '" . $smarty-&gt;_current_file . " compiled at " . date('Y-m-d H:M'). "';";
}
?&gt;

This function can be called from the template as:

{* this function gets executed at compile time only *}
{tplheader}

The resulting PHP code in the compiled template would be something like this:

<php
echo 'index.tpl compiled at 2002-02-20 20:02';
?>

Template Functions

void smarty_function_ name (array $params, object &$smarty)

All attributes passed to template functions from the template are contained in the $params as an associative array. Either access those values directly, e.g. $params['start'] or use extract($params) to import them into the symbol table.

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

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.eightball.php
 * Type:     function
 * Name:     eightball
 * Purpose:  outputs a random magic answer
 * -------------------------------------------------------------
 */
function smarty_function_eightball($params, &$smarty)
{
    $answers = array('Yes',
                     'No',
                     'No way',
                     'Outlook not so good',
                     'Ask again soon',
                     'Maybe in your reality');

    $result = array_rand($answers);
    return $answers[$result];
}
?>

which can be used in the template as:

Question: Will we ever have time travel?
Answer: {eightball}.

Пример 16-2. function plugin without output

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.assign.php
 * Type:     function
 * Name:     assign
 * Purpose:  assign a value to a template variable
 * -------------------------------------------------------------
 */
function smarty_function_assign($params, &$smarty)
{
    extract($params);

    if (empty($var)) {
        $smarty->trigger_error("assign: missing 'var' parameter");
        return;
    }

    if (!in_array('value', array_keys($params))) {
        $smarty->trigger_error("assign: missing 'value' parameter");
        return;
    }

    $smarty->assign($var, $value);
}
?>


Глава 16. Extending Smarty With Plugins

Содержание
How Plugins Work
Naming Conventions
Writing Plugins
Template Functions
Modifiers
Block Functions
Compiler Functions
Prefilters/Postfilters
Output Filters
Resources
Inserts

Version 2.0 introduced the plugin architecture that is used for almost all the customizable functionality of Smarty. This includes:

With the exception of resources, backwards compatibility with the old way of registering handler functions via register_* API is preserved. If you did not use the API but instead modified the class variables $custom_funcs, $custom_mods, and other ones directly, then you will need to adjust your scripts to either use the API or convert your custom functionality into plugins.

How Plugins Work

Plugins are always loaded on demand. Only the specific modifiers, functions, resources, etc invoked in the templates scripts will be loaded. Moreover, each plugin is loaded only once, even if you have several different instances of Smarty running within the same request.

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.


Inserts

Insert plugins are used to implement functions that are invoked by insert tags in the template.

string smarty_insert_ name (array $params, object &$smarty)

The first parameter to the function is an associative array of attributes passed to the insert. Either access those values directly, e.g. $params['start'] or use extract($params) to import them into the symbol table.

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

<?php
/*
 * Smarty plugin
 * ------------------------------------------------------------- 
 * File:     insert.time.php
 * Type:     time
 * Name:     time
 * Purpose:  Inserts current date/time according to format
 * -------------------------------------------------------------
 */
function smarty_insert_time($params, &$smarty)
{
    if (empty($params['format'])) {
        $smarty->trigger_error("insert time: missing 'format' parameter");
        return;
    }

    $datetime = strftime($params['format']);
    return $datetime;
}
?>

Modifiers

Modifiers are little functions that are applied to a variable in the template before it is displayed or used in some other context. Modifiers can be chained together.

mixed smarty_modifier_ name (mixed $value, [mixed $param1, ...])

The first parameter to the modifier plugin is the value on which the modifier is supposed to operate. The rest of the parameters can be optional, depending on what kind of operation is supposed to be performed.

The modifier has to return the result of its processing.

See also register_modifier(), unregister_modifier().

Пример 16-3. simple modifier plugin

This plugin basically aliases one of the built-in PHP functions. It does not have any additional parameters.

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     modifier.capitalize.php
 * Type:     modifier
 * Name:     capitalize
 * Purpose:  capitalize words in the string
 * -------------------------------------------------------------
 */
function smarty_modifier_capitalize($string)
{
    return ucwords($string);
}
?>

Пример 16-4. more complex modifier plugin

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     modifier.truncate.php
 * Type:     modifier
 * Name:     truncate
 * Purpose:  Truncate a string to a certain length if necessary,
 *           optionally splitting in the middle of a word, and 
 *           appending the $etc string.
 * -------------------------------------------------------------
 */
function smarty_modifier_truncate($string, $length = 80, $etc = '...',
                                  $break_words = false)
{
    if ($length == 0)
        return '';

    if (strlen($string) > $length) {
        $length -= strlen($etc);
        $fragment = substr($string, 0, $length+1);
        if ($break_words)
            $fragment = substr($fragment, 0, -1);
        else
            $fragment = preg_replace('/\s+(\S+)?$/', '', $fragment);
        return $fragment.$etc;
    } else
        return $string;
}
?>

Naming Conventions

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.


Output Filters

Output filter plugins operate on a template's output, after the template is loaded and executed, but before the output is displayed.

string smarty_outputfilter_ name (string $template_output, object &$smarty)

The first parameter to the output filter function is the template output that needs to be processed, and the second parameter is the instance of Smarty invoking the plugin. The plugin is supposed to do the processing and return the results.

Пример 16-9. output filter plugin

<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File:     outputfilter.protect_email.php
* Type:     outputfilter
* Name:     protect_email
* Purpose:  Converts @ sign in email addresses to %40 as
*           a simple protection against spambots
* -------------------------------------------------------------
*/
function smarty_outputfilter_protect_email ( $output , & $smarty )
{
     return
preg_replace ( '!(\S+)@([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,3}|[0-9]{1,3}))!' ,
                         
'$1%40$2' , $output );
}
?>

Prefilters/Postfilters

Prefilter and postfilter plugins are very similar in concept; where they differ is in the execution -- more precisely the time of their execution.

string smarty_prefilter_ name (string $source, object &$smarty)

Prefilters are used to process the source of the template immediately before compilation. The first parameter to the prefilter function is the template source, possibly modified by some other prefilters. The plugin is supposed to return the modified source. Note that this source is not saved anywhere, it is only used for compilation.

string smarty_postfilter_ name (string $compiled, object &$smarty)

Postfilters are used to process the compiled output of the template (the PHP code) immediately after the compilation is done but before the compiled template is saved to the filesystem. The first parameter to the postfilter function is the compiled template code, possibly modified by other postfilters. The plugin is supposed to return the modified version of this code.

Пример 16-7. prefilter plugin

&lt;?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     prefilter.pre01.php
 * Type:     prefilter
 * Name:     pre01
 * Purpose:  Convert html tags to be lowercase.
 * -------------------------------------------------------------
 */
 function smarty_prefilter_pre01($source, &$smarty)
 {
     return preg_replace('!&lt;(\w+)[^&gt;]+&gt;!e', 'strtolower("$1")', $source);
 }
?&gt;

Пример 16-8. postfilter plugin

&lt;?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     postfilter.post01.php
 * Type:     postfilter
 * Name:     post01
 * Purpose:  Output code that lists all current template vars.
 * -------------------------------------------------------------
 */
 function smarty_postfilter_post01($compiled, &$smarty)
 {
     $compiled = "&lt;pre&gt;\n&lt;?php print_r(\$this-&gt;get_template_vars()); ?&gt;\n&lt;/pre&gt;" . $compiled;
     return $compiled;
 }
?&gt;

Resources

Resource plugins are meant as a generic way of providing template sources or PHP script components to Smarty. Some examples of resources: databases, LDAP, shared memory, sockets, and so on.

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

<?php
/*
 * Smarty plugin
 * ------------------------------------------------------------- 
 * File:     resource.db.php
 * Type:     resource
 * Name:     db
 * Purpose:  Fetches templates from a database
 * -------------------------------------------------------------
 */
function smarty_resource_db_source($tpl_name, &$tpl_source, &$smarty)
{
    // do database call here to fetch your template,
    // populating $tpl_source
    $sql = new SQL;
    $sql->query("select tpl_source
                   from my_table
                  where tpl_name='$tpl_name'");
    if ($sql->num_rows) {
        $tpl_source = $sql->record['tpl_source'];
        return true;
    } else {
        return false;
    }
}

function smarty_resource_db_timestamp($tpl_name, &$tpl_timestamp, &$smarty)
{
    // do database call here to populate $tpl_timestamp.
    $sql = new SQL;
    $sql->query("select tpl_timestamp
                   from my_table
                  where tpl_name='$tpl_name'");
    if ($sql->num_rows) {
        $tpl_timestamp = $sql->record['tpl_timestamp'];
        return true;
    } else {
        return false;
    }
}

function smarty_resource_db_secure($tpl_name, &$smarty)
{
    // assume all templates are secure
    return true;
}

function smarty_resource_db_trusted($tpl_name, &$smarty)
{
    // not used for templates
}
?>

Writing Plugins

Plugins can be either loaded by Smarty automatically from the filesystem or they can be registered at runtime via one of the register_* API functions. They can also be unregistered by using unregister_* API functions.

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


Предисловие

Несомненно, один из наиболее часто задаваемых вопросов в списках рассылки по 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...


Глава 19. Источники

Домашняя страница Smarty: http://smarty.php.net/ Для подписки на новости, надо послать письмо на smarty-general-subscribe@lists.php.net. Архив подписки доступен на http://marc.theaimsgroup.com/?l=smarty&r=1&w=2.


Cache Handler Function

As an alternative to using the default file-based caching mechanism, you can specify a custom cache handling function that will be used to read, write and clear cached files.

Create a function in your application that Smarty will use as a cache handler. Set the name of it in the $cache_handler_func class variable. Smarty will now use this to handle cached data. The first argument is the action, which will be one of 'read', 'write' and 'clear'. The second parameter is the Smarty object. The third parameter is the cached content. Upon a write, Smarty passes the cached content in these parameters. Upon a 'read', Smarty expects your function to accept this parameter by reference and populate it with the cached data. Upon a 'clear', pass a dummy variable here since it is not used. The fourth parameter is the name of the template file (needed for read/write), the fifth parameter is the cache_id (optional), and the sixth is the compile_id (optional).

Пример 15-5. example using MySQL as a cache source

&lt;?php
/*

example usage:

include('Smarty.class.php');
include('mysql_cache_handler.php');

$smarty = new Smarty;
$smarty-&gt;cache_handler_func = 'mysql_cache_handler';

$smarty-&gt;display('index.tpl');


mysql database is expected in this format:
	
create database SMARTY_CACHE;

create table CACHE_PAGES(
CacheID char(32) PRIMARY KEY,
CacheContents MEDIUMTEXT NOT NULL
);

*/

function mysql_cache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null)
{
	// set db host, user and pass here
	$db_host = 'localhost';
	$db_user = 'myuser';
	$db_pass = 'mypass';
	$db_name = 'SMARTY_CACHE';
	$use_gzip = false;
	
	// create unique cache id
	$CacheID = md5($tpl_file.$cache_id.$compile_id);
	
	if(! $link = mysql_pconnect($db_host, $db_user, $db_pass)) {
		$smarty_obj-&gt;_trigger_error_msg("cache_handler: could not connect to database");
		return false;
	}
	mysql_select_db($db_name);

	switch ($action) {
		case 'read':
			// save cache to database
			$results = mysql_query("select CacheContents from CACHE_PAGES where CacheID='$CacheID'");
			if(!$results) {
				$smarty_obj-&gt;_trigger_error_msg("cache_handler: query failed.");			
			}
			$row = mysql_fetch_array($results,MYSQL_ASSOC);
			
			if($use_gzip && function_exists("gzuncompress")) {
				$cache_contents = gzuncompress($row["CacheContents"]);
			} else {
				$cache_contents = $row["CacheContents"];
			}
			$return = $results;
			break;
		case 'write':
			// save cache to database
			
			if($use_gzip && function_exists("gzcompress")) {
				// compress the contents for storage efficiency
				$contents = gzcompress($cache_content);
			} else {
				$contents = $cache_content;
			}
			$results = mysql_query("replace into CACHE_PAGES values(
							'$CacheID',
							'".addslashes($contents)."')
						");
			if(!$results) {
				$smarty_obj-&gt;_trigger_error_msg("cache_handler: query failed.");			
			}
			$return = $results;
			break;
		case 'clear':
			// clear cache info
			if(empty($cache_id) && empty($compile_id) && empty($tpl_file)) {
				// clear them all
				$results = mysql_query("delete from CACHE_PAGES");			
			} else {
				$results = mysql_query("delete from CACHE_PAGES where CacheID='$CacheID'");			
			}
			if(!$results) {
				$smarty_obj-&gt;_trigger_error_msg("cache_handler: query failed.");			
			}
			$return = $results;
			break;
		default:
			// error, unknown action
			$smarty_obj-&gt;_trigger_error_msg("cache_handler: unknown action \"$action\"");
			$return = false;
			break;
	}
	mysql_close($link);
	return $return;
	
}

?&gt;

Глава 11. Constants

Содержание
SMARTY_DIR

SMARTY_DIR

This should be the full system path to the location of the Smarty class files. If this is not defined, then Smarty will attempt to determine the appropriate value automatically. If defined, the path must end with a slash.

Пример 11-1. SMARTY_DIR

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

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

II. Smarty для дизайнеров шаблонов


III. Smarty для программистов

Содержание
11. Constants
12. Variables
13. Methods
14. Caching
15. Advanced Features
16. Extending Smarty With Plugins

Resources

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

Templates from the $template_dir do not require a template resource, although you can use the file: resource for consistancy. Just supply the path to the template you want to use relative to the $template_dir root directory.

Пример 15-6. using templates from $template_dir

// from PHP script
$smarty->display("index.tpl");
$smarty->display("admin/menu.tpl");
$smarty->display("file:admin/menu.tpl"); // same as one above

{* from within Smarty template *}
{include file="index.tpl"}
{include file="file:index.tpl"} {* same as one above *}

Templates from any directory

Templates outside of the $template_dir require the file: template resource type, followed by the absolute path and name of the template.

Пример 15-7. using templates from any directory

// from PHP script
$smarty->display("file:/export/templates/index.tpl");
$smarty->display("file:/path/to/my/templates/menu.tpl");

{* from within Smarty template *}
{include file="file:/usr/local/share/templates/navigation.tpl"}

Windows Filepaths

If you are using a Windows machine, filepaths usually include a drive letter (C:) at the beginning of the pathname. Be sure to use "file:" in the path to avoid namespace conflicts and get the desired results.

Пример 15-8. using templates from windows file paths

// from PHP script
$smarty->display("file:C:/export/templates/index.tpl");
$smarty->display("file:F:/path/to/my/templates/menu.tpl");

{* from within Smarty template *}
{include file="file:D:/usr/local/share/templates/navigation.tpl"}

Templates from other sources

You can retrieve templates using whatever possible source you can access with PHP: databases, sockets, LDAP, and so on. You do this by writing resource plugin functions and registering them with Smarty.

See resource plugins section for more information on the functions you are supposed to provide.

Замечание: Note 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

// from PHP script

// put these function somewhere in your application
function db_get_template ($tpl_name, &amp;$tpl_source, &amp;$smarty_obj)
{
    // do database call here to fetch your template,
    // populating $tpl_source
    $sql = new SQL;
    $sql->query("select tpl_source
                   from my_table
                  where tpl_name='$tpl_name'");
    if ($sql->num_rows) {
        $tpl_source = $sql->record['tpl_source'];
        return true;
    } else {
        return false;
    }
}

function db_get_timestamp($tpl_name, &amp;$tpl_timestamp, &amp;$smarty_obj)
{
    // do database call here to populate $tpl_timestamp.
    $sql = new SQL;
    $sql->query("select tpl_timestamp
                   from my_table
                  where tpl_name='$tpl_name'");
    if ($sql->num_rows) {
        $tpl_timestamp = $sql->record['tpl_timestamp'];
        return true;
    } else {
        return false;
    }
}

function db_get_secure($tpl_name, &$smarty_obj)
{
    // assume all templates are secure
    return true;
}

function db_get_trusted($tpl_name, &$smarty_obj)
{
    // not used for templates
}

// register the resource name "db"
$smarty->register_resource("db", array("db_get_template",
                                       "db_get_timestamp",
                                       "db_get_secure",
                                       "db_get_trusted"));

// using resource from php script
$smarty->display("db:index.tpl");

{* using resource from within Smarty template *}
{include file="db:/extras/navigation.tpl"}

Default template handler function

You can specify a function that is used to retrieve template contents in the event the template cannot be retrieved from its resource. One use of this is to create templates that do not exist on-the-fly.

Пример 15-10. using the default template handler function

<?php
// put this function somewhere in your application

function make_template ($resource_type, $resource_name, &$template_source, &$template_timestamp, &$smarty_obj)
{
	if( $resource_type == 'file' ) {
		if ( ! is_readable ( $resource_name )) {
			// create the template file, return contents.
			$template_source = "This is a new template.";
			$template_timestamp = time();
			$smarty_obj->_write_file($resource_name,$template_source);
			return true;
		}
    } else {
		// not a file
		return false;
    }
}

// set the default handler
$smarty->default_template_handler_func = 'make_template';
?>

Составные шаблоны

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

{* Smarty *}

{php}

	// setup our function for fetching stock data
	function fetch_ticker($symbol,&$ticker_name,&$ticker_price) {
		// put logic here that fetches $ticker_name
		// and $ticker_price from some resource
	}

	// call the function
	fetch_ticker("YHOO",$ticker_name,$ticker_price);
	
	// assign template variables
    $this->assign("ticker_name",$ticker_name);
    $this->assign("ticker_price",$ticker_price);

{/php}

Stock Name: {$ticker_name} Stock Price: {$ticker_price}

As of Smarty 1.5.0, there is even a cleaner way. You can include php in your templates with the {include_php ...} tag. This way you can keep your PHP logic separated from the template logic. See the include_php function for more information.

Пример 18-8. componentized template with include_php

load_ticker.php
---------------

&lt;?php
	// setup our function for fetching stock data
	function fetch_ticker($symbol,&$ticker_name,&$ticker_price) {
		// put logic here that fetches $ticker_name
		// and $ticker_price from some resource
	}

	// call the function
	fetch_ticker("YHOO",$ticker_name,$ticker_price);
	
	// assign template variables
    $this->assign("ticker_name",$ticker_name);
    $this->assign("ticker_price",$ticker_price);
?&gt;


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

{* Smarty *}

{include_php file="load_ticker.php"}

Stock Name: {$ticker_name} Stock Price: {$ticker_price}

Обработка переменных по умлочанию

Если переменная встречается часто, то использование модификатора default каждый раз можно избежать, используя функцию assign.

Пример 18-2. Назначение переменной шаблона значения по умолчанию

{* вверху шаблона *}
{assign var="title" value=$title|default:"no title"}

{* если переменная $title была пустой, то сейчас она содержит "no title" *}
{$title}

Присвоение переменной заголовка (title) заголовку шаблона.

Если большинство ваших шаблонов имеют похожие верхние и нижние части, то имеет смысл вынести их в отдельные файлы. Но если шапка должна иметь различные заголовки на различных страницах? Смотрите пример ниже.

Пример 18-3. Присвоение переменной заголовка (title) заголовку шаблона.

mainpage.tpl
------------

{include file="header.tpl" title="Main Page"}
{* тело шаблона *}
{include file="footer.tpl"}


archives.tpl
------------

{config_load file="archive_page.conf"}
{include file="header.tpl" title=#archivePageTitle#}
{* тело шаблонаe *}
{include file="footer.tpl"}


header.tpl
----------
<HTML>
 <HEAD>
  <TITLE>{$title|default:"BC News"}</TITLE>
  </HEAD>
  <BODY>


footer.tpl
----------
</BODY>
</HTML>

Если выводится главная страница, то заголовок будет "Main Page", если архивы, то заголовк берется из файла конфигурации. Если заголовок будет пустой, то выведется значение по умолчанию "BC News".


WAP/WML

WAP/WML шаблоны требуют, чтобы заголовок Content-type был передан вместе с шаблоном. Простейший путь - написать пользовательскую функцию, которая будет выводить заголовки. Так как мы будем пользоваться тэгами insert, то заголовки не будут кэшироваться. Так же ничего не должно выводиться в браузер до шаблона, иначе заголовки могут быть неправильно восприняты.

Пример 18-6. Использование insert для записи WML Content-Type заголовков

// поместите эту функцию в приложение, или в  Smarty.addons.php
function insert_header() {
    // this function expects $content argument
    extract(func_get_arg(0));
    if(empty($content))
        return;
    header($content);
    return;
}

// шаблон ДОЛЖЕН начинаться с тэга insert. Пример:
{insert name=header content="Content-Type: text/vnd.wap.wml"}

<?xml version="1.0"?>  
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml"> 

<!-- begin new wml deck --> 
<wml> 
<!-- begin first card --> 
<card> 
<do type="accept"> 
<go href="#two"/> 
</do>  
<p> 
Welcome to WAP with Smarty!
Press OK to continue...  
</p> 
</card>  
<!-- begin second card --> 
<card id="two">  
<p> 
Pretty easy isn't it?
</p> 
</card> 
</wml>

Глава 17. Troubleshooting

Содержание
Smarty/PHP errors

Smarty/PHP errors

Smarty can catch many errors such as missing tag attributes or malformed variable names. If this happens, you will see an error similar to the following:

Пример 17-1. Smarty errors

Warning: Smarty: [in index.tpl line 4]: syntax error: unknown tag - '%blah'
in /path/to/smarty/Smarty.class.php on line 1041

Fatal error: Smarty: [in index.tpl line 28]: syntax error: missing section name
in /path/to/smarty/Smarty.class.php on line 1041

Smarty shows you the template name, the line number and the error. After that, the error consists of the actual line number in the Smarty class that the error occured.

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.

Пример 17-2. PHP parsing errors

Parse error: parse error in /path/to/smarty/templates_c/index.tpl.php on line 75

When you encounter a PHP parsing error, the error line number will correspond to the compiled PHP script, not the template itself. Usually you can look at the template and spot the syntax error. Here are some common things to look for: missing close tags for {if}{/if} or {section}{/section}, or syntax of logic within an {if} tag. If you can't find the error, you might have to open the compiled PHP file and go to the line number to figure out where the corresponding error is in the template.


$autoload_filters

If there are some filters that you wish to load on every template invocation, you can specify them using this variable and Smarty will automatically load them for you. The variable is an associative array where keys are filter types and values are arrays of the filter names. For example:

$smarty->autoload_filters = array('pre' => array('trim', 'stamp'),
                                  'output' => array('convert'));


$cache_dir

This is the name of the directory where template caches are stored. By default this is "./cache", meaning that it will look for the cache directory in the same directory as the executing php script. You can also use your own custom cache handler function to control cache files, which will ignore this setting.

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.


$cache_handler_func

You can supply a custom function to handle cache files instead of using the built-in method using the $cache_dir. See the custom cache handler function section for details.


$cache_lifetime

This is the length of time in seconds that a template cache is valid. Once this time has expired, the cache will be regenerated. $caching must be set to "true" for $cache_lifetime to have any purpose. A value of -1 will force the cache to never expire. A value of 0 will cause the cache to always regenerate (good for testing only, to disable caching a more efficient method is to set $caching = false.)

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_modified_check

If set to true, Smarty will respect the If-Modified-Since header sent from the client. If the cached file timestamp has not changed since the last visit, then a "304 Not Modified" header will be sent instead of the content. This works only on cached content without insert tags.


$caching

This tells Smarty whether or not to cache the output of the templates. By default this is set to 0, or disabled. If your templates generate redundant redundant content, it is advisable to turn on caching. This will result in significant performance gains. You can also have multiple caches for the same template. A value of 1 or 2 enables caching. 1 tells Smarty to use the current $cache_lifetime variable to determine if the cache has expired. A value of 2 tells Smarty to use the cache_lifetime value at the time the cache was generated. This way you can set the cache_lifetime just before fetching the template to have granular control over when that particular cache expires. See also is_cached.

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.


$compile_check

Upon each invocation of the PHP application, Smarty tests to see if the current template has changed (different time stamp) since the last time it was compiled. If it has changed, it recompiles that template. If the template has not been compiled, it will compile regardless of this setting. By default this variable is set to true. Once an application is put into production (templates won't be changing), the compile_check step is no longer needed. Be sure to set $compile_check to "false" for maximal performance. Note that if you change this to "false" and a template file is changed, you will *not* see the change since the template will not get recompiled. If caching is enabled and compile_check is enabled, then the cache files will get regenerated if an involved template file or config file was updated. See $force_compile or clear_compiled_tpl.


$security

$security true/false, default is false. Security is good for situations when you have untrusted parties editing the templates (via ftp for example) and you want to reduce the risk of system security compromises through the template language. Turning on security enforces the following rules to the template language, unless specifially overridden with $security_settings:


$security_settings

These are used to override or specify the security settings when security is enabled. These are the possible settings:


$compile_dir

This is the name of the directory where compiled templates are located. By default this is "./templates_c", meaning that it will look for the compile directory in the same directory as the executing php script.

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.


$compile_id

Persistant compile identifier. As an alternative to passing the same compile_id to each and every function call, you can set this compile_id and it will be used implicitly thereafter.


$compiler_class

Specifies the name of the compiler class that Smarty will use to compile the templates. The default is 'Smarty_Compiler'. For advanced users only.


$config_booleanize

If set to true, config file values of on/true/yes and off/false/no get converted to boolean values automatically. This way you can use the values in the template like so: {if #foobar#} ... {/if}. If foobar was on, true or yes, the {if} statement will execute. true by default.


$config_dir

This is the directory used to store config files used in the templates. Default is "./configs", meaning that it will look for the configs directory in the same directory as the executing php script.

Technical Note: It is not recommended to put this directory under the web server document root.


$config_fix_newlines

If set to true, mac and dos newlines (\r and \r\n) in config files are converted to \n when they are parsed. true by default.


$config_overwrite

If set to true, variables read in from config files will overwrite each other. Otherwise, the variables will be pushed onto an array. This is helpful if you want to store arrays of data in config files, just list each element multiple times. true by default.


$config_read_hidden

If set to true, hidden sections (section names beginning with a period) in config files can be read from templates. Typically you would leave this false, that way you can store sensitive data in the config files such as database parameters and not worry about the template loading them. false by default.


$debug_tpl

This is the name of the template file used for the debugging console. By default, it is named debug.tpl and is located in the SMARTY_DIR.


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


$debugging

This enables the debugging console. The console is a javascript window that informs you of the included templates and assigned variables for the current template page.


$default_modifiers

This is an array of modifiers to implicitly apply to every variable in a template. For example, to HTML-escape every variable by default, use array('escape:"htmlall"'); To make a variable exempt from default modifiers, pass the special "smarty" modifier with a parameter value of "nodefaults" modifier to it, such as {$var|smarty:nodefaults}.


$default_template_handler_func

This function is called when a template cannot be obtained from its resource.


$force_compile

This forces Smarty to (re)compile templates on every invocation. This setting overrides $compile_check. By default this is disabled. This is handy for development and debugging. It should never be used in a production environment. If caching is enabled, the cache file(s) will be regenerated every time.


$global_assign

This is a list of variables that are always implicitly assigned to the template engine. This is handy for making global variables or server variables available to all templates without having to manually assign them. Each element in the $global_assign should be either a name of the global variable, or a key/value pair, where the key is the name of the global array and the value is the array of variables to be assigned from that global array. $SCRIPT_NAME is globally assigned by default from $HTTP_SERVER_VARS.

Technical Note: Server variables can be accessed through the $smarty variable, such as {$smarty.server.SCRIPT_NAME}. See the section on the $smarty variable.


$left_delimiter

This is the left delimiter used by the template language. Default is "{".


$php_handling

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.

NOTE: Embedding PHP code into templates is highly discouraged. Use custom functions or modifiers instead.


$plugins_dir

This is the directories where Smarty will look for the plugins that it needs. Default is "plugins" under the SMARTY_DIR. If you supply a relative path, Smarty will first look under the SMARTY_DIR, then relative to the cwd (current working directory), then relative to each entry in your PHP include path.

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.


$request_vars_order

The order in which request variables are registered, similar to variables_order in php.ini


$right_delimiter

This is the right delimiter used by the template language. Default is "}".


$secure_dir

This is an array of all local directories that are considered secure. {include} and {fetch} use this when security is enabled.


$trusted_dir

$trusted_dir is only for use when $security is enabled. This is an array of all directories that are considered trusted. Trusted directories are where you keep php scripts that are executed directly from the templates with {include_php}.


$undefined

This sets the value of $undefined for Smarty, default is null. Currently this is only used to set undefined variables in $global_assign to a default value.


$use_sub_dirs

Set this to false if your PHP environment does not allow the creation of sub directories by Smarty. Sub directories are more efficient, so use them if you can.


Глава 1. Что такое Smarty?

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: