Smarty For ProgrammersConstantsSMARTY_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.
SMARTY_DIR
// set path to Smarty directory
define("SMARTY_DIR","/usr/local/lib/php/Smarty/");
require_once(SMARTY_DIR."Smarty.class.php");Variables$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.
$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.
$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.
$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.
$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.
$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.
$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.
$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.
$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'));
$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.
$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.
$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.
$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_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_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_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.
$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_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_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.
$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.
$default_template_handler_func
This function is called when a template cannot be obtained from
its resource.
$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.
SMARTY_PHP_PASSTHRU - Smarty echos tags as-is.SMARTY_PHP_QUOTE - Smarty quotes the tags as
html entities.SMARTY_PHP_REMOVE - Smarty removes the tags from
the templates.SMARTY_PHP_ALLOW - Smarty will execute the tags
as PHP code.
NOTE: Embedding PHP code into templates is highly discouraged.
Use custom functions or
modifiers instead.
$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:
If $php_handling is set to SMARTY_PHP_ALLOW, this is
implicitly changed to SMARTY_PHP_PASSTHRUPHP functions are not allowed in IF statements,
except those specified in the $security_settingstemplates can only be included from directories
listed in the $secure_dir arraylocal files can only be fetched from directories
listed in the $secure_dir array using {fetch}{php}{/php} tags are not allowedPHP functions are not allowed as modifiers, except
those specified in the $security_settings$secure_dir
This is an array of all local directories that are considered
secure. {include} and {fetch} use this when security is enabled.
$security_settings
These are used to override or specify the security settings when
security is enabled. These are the possible settings:
PHP_HANDLING - true/false. If set to true, the
$php_handling setting is not checked for security.IF_FUNCS - This is an array of the names of permitted
PHP functions in IF statements.INCLUDE_ANY - true/false. If set to true, any
template can be included from the file system, regardless of the
$secure_dir list.PHP_TAGS - true/false. If set to true, {php}{/php}
tags are permitted in the templates.MODIFIER_FUNCS - This is an array of the names of permitted
PHP functions used as variable modifiers.$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}.
$left_delimiter
This is the left delimiter used by the template language.
Default is "{".
$right_delimiter
This is the right delimiter used by the template language.
Default is "}".
$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.
$request_vars_order
The order in which request variables are registered, similar to
variables_order in php.ini
$request_use_auto_globals
Specifies if Smarty should use php's $HTTP_*_VARS[]
($request_use_auto_globals=false which is the default value) or
$_*[] ($request_use_auto_globals=true). This affects templates
that make use of {$smarty.request.*}, {$smarty.get.*} etc. .
Caution: If you set $request_use_auto_globals to true, variable.request.vars.order
has no effect but php's configuration value
gpc_order is used.
$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.
$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.
$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_resource_type
This tells smarty what resource type to use implicitly. The default value
is 'file', meaning that $smarty->display('index.tpl'); and
$smarty->display('file:index.tpl'); are identical in meaning. See the
resource chapter for details.
Methodsappendvoid appendmixed varvoid appendstring varnamemixed varvoid appendstring varnamemixed varboolean 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.
append
// passing name/value pairs
$smarty->append("Name","Fred");
$smarty->append("Address",$address);
// passing an associative array
$smarty->append(array("city" => "Lincoln","state" => "Nebraska"));append_by_refvoid append_by_refstring varnamemixed varvoid append_by_refstring varnamemixed varboolean 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.
append_by_ref
// appending name/value pairs
$smarty->append_by_ref("Name",$myname);
$smarty->append_by_ref("Address",$address);assignvoid assignmixed varvoid assignstring varnamemixed 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.
assign
// passing name/value pairs
$smarty->assign("Name","Fred");
$smarty->assign("Address",$address);
// passing an associative array
$smarty->assign(array("city" => "Lincoln","state" => "Nebraska"));assign_by_refvoid assign_by_refstring varnamemixed 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.
assign_by_ref
// passing name/value pairs
$smarty->assign_by_ref("Name",$myname);
$smarty->assign_by_ref("Address",$address);clear_all_assignvoid clear_all_assign
This clears the values of all assigned variables.
clear_all_assign
// clear all assigned variables
$smarty->clear_all_assign();clear_all_cachevoid clear_all_cacheint 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.
clear_all_cache
// clear the entire cache
$smarty->clear_all_cache();clear_assignvoid clear_assignstring var
This clears the value of an assigned variable. This
can be a single value, or an array of values.
clear_assign
// clear a single variable
$smarty->clear_assign("Name");
// clear multiple variables
$smarty->clear_assign(array("Name","Address","Zip"));clear_cachevoid clear_cachestring templatestring cache idstring compile idint 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.
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_tplvoid clear_compiled_tplstring 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.
clear_compiled_tpl
// clear a specific template resource
$smarty->clear_compiled_tpl("index.tpl");
// clear entire compile directory
$smarty->clear_compiled_tpl();clear_configvoid clear_configstring var
This clears all assigned config variables. If a variable name is
supplied, only that variable is cleared.
clear_config
// clear all assigned config variables.
$smarty->clear_config();
// clear one variable
$smarty->clear_config('foobar');config_loadvoid config_loadstring filestring 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.
config_load
// load config variables and assign them
$smarty->config_load('my.conf');
// load a section
$smarty->config_load('my.conf','foobar');displayvoid displaystring templatestring cache_idstring 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().
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.
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");fetchstring fetchstring templatestring cache_idstring 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().
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;get_config_varsarray get_config_varsstring varname
This returns the given loaded config variable value. If no parameter
is given, an array of all loaded config variables is returned.
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_objectarray get_registered_objectstring 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.
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_varsarray get_template_varsstring varname
This returns the given assigned variable value. If no parameter
is given, an array of all assigned variables is returned.
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_cachedvoid is_cachedstring 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.
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 an optional second parameter
in case you want multiple caches for the given template.
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_filtervoid load_filterstring typestring 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'.
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_blockvoid register_blockstring namemixed implbool cacheablearray or null cache_attrs
Use this to dynamically register block functions plugins.
Pass in the block function name, followed by the PHP
function callback that implements it.
The php-function callback impl can be either (a) a string
containing the function name or (b) an array of the form
array(&$object, $method) with
&$object being a reference to an
object and $method being a string
containing the mehod-name or (c) an array of the form
array(&$class, $method) with
$class being a classname and
$method being a class method of that
class.
$cacheable and $cache_attrs can be omitted in most cases. See Controlling Cacheability of Plugins' Output on how to use them properly.
register_block
/* PHP */
$smarty->register_block("translate", "do_translation");
function do_translation ($params, $content, &$smarty, &$repeat) {
if (isset($content)) {
$lang = $params['lang'];
// do some translation with $content
return $translation;
}
}
{* template *}
{translate lang="br"}
Hello, world!
{/translate}register_compiler_functionvoid register_compiler_functionstring namemixed implbool cacheable
Use this to dynamically register a compiler function plugin.
Pass in the compiler function name, followed by the PHP
function that implements it.
The php-function callback impl can be either (a) a string
containing the function name or (b) an array of the form
array(&$object, $method) with
&$object being a reference to an
object and $method being a string
containing the mehod-name or (c) an array of the form
array(&$class, $method) with
$class being a classname and
$method being a class method of that
class.
$cacheable can be omitted in
most cases. See Controlling
Cacheability of Plugins' Output on how to it properly.
register_functionvoid register_functionstring namemixed implbool cacheablearray or null cache_attrs
Use this to dynamically register template function plugins.
Pass in the template function name, followed by the PHP
function name that implements it.
The php-function callback impl can be either (a) a string
containing the function name or (b) an array of the form
array(&$object, $method) with
&$object being a reference to an
object and $method being a string
containing the mehod-name or (c) an array of the form
array(&$class, $method) with
$class being a classname and
$method being a class method of that
class.
$cacheable and $cache_attrs can be omitted in most cases. See Controlling Cacheability of Plugins' Output on how to use them properly.
register_function
$smarty->register_function("date_now", "print_current_date");
function print_current_date ($params) {
extract($params);
if(empty($format))
$format="%b %e, %Y";
return 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_modifiervoid register_modifierstring namemixed impl
Use this to dynamically register modifier plugin. Pass in the
template modifier name, followed by the PHP function that it
implements it.
The php-function callback impl can be either (a) a string
containing the function name or (b) an array of the form
array(&$object, $method) with
&$object being a reference to an
object and $method being a string
containing the mehod-name or (c) an array of the form
array(&$class, $method) with
$class being a classname and
$method being a class method of that
class.
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 variablesregister_objectvoid register_objectstring object_nameobject $objectarray allowed methods/propertiesboolean formatarray block methods
This is to register an object for use in the templates. See the
object section
of the manual for examples.
register_outputfiltervoid register_outputfiltermixed function
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.
The php-function callback function can be either (a) a string
containing the function name or (b) an array of the form
array(&$object, $method) with
&$object being a reference to an
object and $method being a string
containing the mehod-name or (c) an array of the form
array(&$class, $method) with
$class being a classname and
$method being a class method of that
class.
register_postfiltervoid register_postfiltermixed function
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.
The php-function callback function can be either (a) a string
containing the function name or (b) an array of the form
array(&$object, $method) with
&$object being a reference to an
object and $method being a string
containing the mehod-name or (c) an array of the form
array(&$class, $method) with
$class being a classname and
$method being a class method of that
class.
register_prefiltervoid register_prefiltermixed function
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.
The php-function callback function can be either (a) a string
containing the function name or (b) an array of the form
array(&$object, $method) with
&$object being a reference to an
object and $method being a string
containing the mehod-name or (c) an array of the form
array(&$class, $method) with
$class being a classname and
$method being a class method of that
class.
register_resourcevoid register_resourcestring namearray 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.
Technical Note
A resource name must be at least two characters in length. One
character resource names will be ignored and used as part of the file
path, such as $smarty->display('c:/path/to/index.tpl');
The php-function-array resource_funcs
must have 4 or 5 elements. With 4 elements the elements are
the functions-callbacks for the respective "source",
"timestamp", "secure" and "trusted" functions of the
resource. With 5 elements the first element has to be an
object reference or a class name of the object or class
implementing the resource and the 4 following elements have
to be the method names implementing "source", "timestamp",
"secure" and "trusted".
register_resource
$smarty->register_resource("db", array("db_get_template",
"db_get_timestamp",
"db_get_secure",
"db_get_trusted"));trigger_errorvoid trigger_errorstring 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.
template_existsbool template_existsstring 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.
unregister_blockvoid unregister_blockstring name
Use this to dynamically unregister block function plugin.
Pass in the block function name.
unregister_compiler_functionvoid unregister_compiler_functionstring name
Use this to dynamically unregister a compiler function. Pass in
the name of the compiler function.
unregister_functionvoid unregister_functionstring name
Use this to dynamically unregister template function plugin.
Pass in the template function name.
unregister_function
// we don't want template designers to have access to system files
$smarty->unregister_function("fetch");unregister_modifiervoid unregister_modifierstring name
Use this to dynamically unregister modifier plugin. Pass in the
template modifier name.
unregister_modifier
// we don't want template designers to strip tags from elements
$smarty->unregister_modifier("strip_tags");unregister_objectvoid unregister_objectstring object_name
Use this to unregister an object.
unregister_outputfiltervoid unregister_outputfilterstring function_name
Use this to dynamically unregister an output filter.
unregister_postfiltervoid unregister_postfilterstring function_name
Use this to dynamically unregister a postfilter.
unregister_prefiltervoid unregister_prefilterstring function_name
Use this to dynamically unregister a prefilter.
unregister_resourcevoid unregister_resourcestring name
Use this to dynamically unregister a resource plugin. Pass in the
name of the resource.
unregister_resource
$smarty->unregister_resource("db");Caching
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.)
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.
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.
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.
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.
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');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.
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().
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().
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.
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.
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');
Controlling Cacheability of Plugins' Output
Since Smarty-2.6.0 plugins the cacheability of plugins can be declared
when registering them. The third parameter to register_block,
register_compiler_function and register_function is called
$cacheable and defaults to true which is also
the behaviour of plugins in Smarty versions before 2.6.0
When registering a plugin with $cacheable=false the plugin is called everytime the page is displayed, even if the page comes from the cache. The plugin function behaves a little like an insert function.
In contrast to {insert} the attributes to the plugins are not cached by default. They can be declared to be cached with the fourth parameter $cache_attrs. $cache_attrs is an array of attribute-names that should be cached, so the plugin-function get value as it was the time the page was written to cache everytime it is fetched from the cache.
Preventing a plugin's output from being cached
index.php:
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
function remaining_seconds($params, &$smarty) {
$remain = $params['endtime'] - time();
if ($remain >=0)
return $remain . " second(s)";
else
return "done";
}
$smarty->register_function('remaining', 'remaining_seconds', false, array('endtime'));
if (!$smarty->is_cached('index.tpl')) {
// fetch $obj from db and assign...
$smarty->assign_by_ref('obj', $obj);
}
$smarty->display('index.tpl');
index.tpl:
Time Remaining: {remain endtime=$obj->endtime}
The number of seconds till the endtime of $obj is reached changes on each display of the page, even if the page is cached. Since the endtime attribute is cached the object only has to be pulled from the database when page is written to the cache but not on subsequent requests of the page.
Preventing a whole passage of a template from being cached
index.php:
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
function smarty_block_dynamic($param, $content, &$smarty) {
return $content;
}
$smarty->register_block('dynamic', 'smarty_block_dynamic', false);
$smarty->display('index.tpl');
index.tpl:
Page created: {"0"|date_format:"%D %H:%M:%S"}
{dynamic}
Now is: {"0"|date_format:"%D %H:%M:%S"}
... do other stuff ...
{/dynamic}
When reloading the page you will notice that both dates differ. One is "dynamic" one is "static". You can do everything between {dynamic}...{/dynamic} and be sure it will not be cached like the rest of the page.
Advanced FeaturesObjects
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.
The optional fifth parameter has only effect with
format being true
and contains a list ob methods that should be treated as
blocks. That means these methods have a closing tag in the
template
({foobar->meth2}...{/foobar->meth2}) and
the parameters to the methods have the same synopsis as the
parameters for block-function-plugins: They get 4 parameters
$params,
$content,
&$smarty and
&$repeat and they also behave like
block-function-plugins.
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)}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.
using a template prefilter
<?php
// put this in your application
function remove_dw_comments($tpl_source, &$smarty)
{
return preg_replace("/<!--#.*-->/U","",$tpl_source);
}
// register the prefilter
$smarty->register_prefilter("remove_dw_comments");
$smarty->display("index.tpl");
?>
{* Smarty template index.tpl *}
<!--# this line will get removed by the prefilter -->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.
using a template postfilter
<?php
// put this in your application
function add_header_comment($tpl_source, &$smarty)
{
return "<?php echo \"<!-- Created by Smarty! -->\n\" ?>\n".$tpl_source;
}
// register the postfilter
$smarty->register_postfilter("add_header_comment");
$smarty->display("index.tpl");
?>
{* compiled Smarty template index.tpl *}
<!-- Created by Smarty! -->
{* rest of template content... *}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.
using a template outputfilter
<?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
?>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).
example using MySQL as a cache source
<?php
/*
example usage:
include('Smarty.class.php');
include('mysql_cache_handler.php');
$smarty = new Smarty;
$smarty->cache_handler_func = 'mysql_cache_handler';
$smarty->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->_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->_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->_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->_trigger_error_msg("cache_handler: query failed.");
}
$return = $results;
break;
default:
// error, unknown action
$smarty_obj->_trigger_error_msg("cache_handler: unknown action \"$action\"");
$return = false;
break;
}
mysql_close($link);
return $return;
}
?>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. If a resource is not explicitly given the value of $default_resource_type is
assumed.
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.
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.
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.
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.
using custom resources
// from PHP script
// put these function somewhere in your application
function db_get_template ($tpl_name, &$tpl_source, &$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, &$tpl_timestamp, &$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.
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';
?>Extending Smarty With Plugins
Version 2.0 introduced the plugin architecture that is used
for almost all the customizable functionality of Smarty. This includes:
functionsmodifiersblock functionscompiler functionsprefilterspostfiltersoutputfiltersresourcesinserts
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.
The plugins directory
can be a string containing a path or an array containing multiple
paths. To install a plugin, simply place it in one of the
directories and Smarty will use it automatically.
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:
functionmodifierblockcompilerprefilterpostfilteroutputfilterresourceinsert
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.
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->_get_plugin_filepath('function', 'html_options');
As a general rule, Smarty object is always passed to the plugins
as the last parameter (with two exceptions: modifiers do not get
passed the Smarty object at all and blocks get passed
&$repeat after the Smarty object to keep
backwards compatibility to older versions of Smarty).
Template Functionsvoid smarty_function_namearray $paramsobject &$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().
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}.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);
}
?>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_namemixed $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().
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);
}
?>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;
}
?>Block Functionsvoid smarty_block_namearray $paramsmixed $contentobject &$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}.
By default your function implementation is called twice by
Smarty: once for the opening tag, and once for the closing tag
(see &$repeat below how to change this).
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.
The parameter &$repeat is passed by
reference to the function implementation and provides a
possibility for it to control how many times the block is
displayed. By default $repeat is
true at the first call of the block-function
(the block opening tag) and false on all
subsequent calls to the block function (the block's closing tag).
Each time the function implementation returns with
&$repeat being true, the contents between
{func} .. {/func} are evaluated and the function implementation
is called again with the new block contents in the parameter
$content.
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().
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 (isset($content)) {
$lang = $params['lang'];
// do some intelligent translation thing here with $content
return $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_namestring $tag_argobject &$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().
simple compiler function
<?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->_current_file . " compiled at " . date('Y-m-d H:M'). "';";
}
?>
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';
?>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_namestring $sourceobject &$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_namestring $compiledobject &$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.
prefilter plugin
<?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('!<(\w+)[^>]+>!e', 'strtolower("$1")', $source);
}
?>postfilter plugin
<?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 = "<pre>\n<?php print_r(\$this->get_template_vars()); ?>\n</pre>" . $compiled;
return $compiled;
}
?>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_namestring $template_outputobject &$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.
output filter plugin
/*
* 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);
}
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_sourcestring $rsrc_namestring &$sourceobject &$smartybool smarty_resource_name_timestampstring $rsrc_nameint &$timestampobject &$smartybool smarty_resource_name_securestring $rsrc_nameobject &$smartybool smarty_resource_name_trustedstring $rsrc_nameobject &$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().
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
}
?>Inserts
Insert plugins are used to implement functions that are invoked by
insert
tags in the template.
string smarty_insert_namearray $paramsobject &$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.
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;
}
?>