The most fundamental concept when writing templates is how to output a variable. All variable names are preceded by a dollar symbol. To output a variable, surround its name with curly braces. The following listing demonstrates this.
Example A.1. Outputting a variable called $title
<html> <head> <title>{$title}</title> </head> <body> ... </body> </html>
This is the most common way to use templates. You can output variables in this manner for all types apart from arrays and associative arrays; with arrays you will typically loop over the array and then output each value, whereas with associative arrays you will access one of the values in the array directly.
Modifiers allow you to make a last minute change to a variable
when outputting it. This is achieved by adding a pipe symbol (|
)
and the modifier name after the variable name.
For example, if you have a modifier called date_format
, you
could modify the variable $timestamp
using
{$timestamp|date_format}
. If the $timestamp
variable originally contained a timestamp value, then this may result in output such
as Jan 1, 2010
.
There are a number of modifiers available, each of which is documented in the
Smarty Template Engine manual. Two useful examples of these are
escape
and date_format
.
Escaping content is the process of modifying variable content to ensure your site displays content correctly and is not susceptible to cross-site scripting (XSS) or cross-site request forgeries (CSRF). It is also useful for ensuring your site remains a valid HTML document.
When you escape content, you prevent HTML tags being output in your
variables. This is achieved with the escape
modifier. A
good example of this is when your variable contains an ampersand (&).
Example A.2. Escaping content to maintain standards compliance.
<html> <head> <title>{$title|escape}</title> </head> <body> ... </body> </html>
In several of the template types there is date/time data made available for
output. This value is in a special timestamp format, but you can output the
timestamp into a "human-readable" format using the
date_format
modifier.
You can optionally pass an argument to date_format
which
indicates how the timestamp should be formatted. A full list of the available
formatting strings are available at .
The following examples use the built-in $smarty.now
timestamp. You can use this variable for the current date/time.
Example A.3. Outputting timestamps using date_format
.
Jan 1, 2010 {$smarty.now|date_format} 1 January 2010 {$smarty.now|date_format:'%e %B %Y'} 12:00:00 {$smarty.now|date_format:'%T'} 1 January 2010 @ 12:00:00 {$smarty.now|date_format:'%e %B %Y @ %T'}