Documentation
Documentation
Table of Contents []
Preface []
I. Getting Started []
1. What is Smarty? [Smaty?]
2. Installation []
Requirements []
Basic Installation []
Extended Setup []
II. Smarty For Template Designers []
3. Basic Syntax []
Comments []
Functions []
Attributes []
Embedding Vars in Double Quotes []
Math []
4. Variables []
Variables assigned from PHP [PHP]
Variables loaded from config files []
{$smarty} reserved variable [{$smarty}]
5. Variable Modifiers []
capitalize []
count_characters []
cat []
count_paragraphs []
count_sentences []
count_words []
date_format []
default []
escape []
indent []
lower []
nl2br [ <br />]
regex_replace []
replace []
spacify []
string_format []
strip [()]
strip_tags [html]
truncate []
upper []
wordwrap []
6. Combining Modifiers []
7. Built-in Functions []
capture
config_load
foreach,foreachelse
include
include_php
insert
if,elseif,else
ldelim,rdelim
literal
php
section,sectionelse
strip
8. Custom Functions []
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. Config Files []
10. Debugging Console []
III. Smarty For Programmers []
11. Constants []
SMARTY_DIR [Smarty]
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 [php]
$security []
$secure_dir []
$security_settings []
$trusted_dir []
$left_delimiter []
$right_delimiter []
$compiler_class []
$request_vars_order []
$request_use_auto_globals []
$compile_id [id]
$use_sub_dirs []
$default_modifiers []
$default_resource_type []
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 []
Controlling Cacheability of Plugins' Output []
15. Advanced Features []
Objects []
Prefilters []
Postfilters []
Output Filters []
Cache Handler Function []
Resources []
16. Extending Smarty With Plugins [Smarty]
How Plugins Work []
Naming Conventions []
Writing Plugins []
Template Functions []
Modifiers []
Block Functions []
Compiler Functions []
Prefilters/Postfilters [/]
Output Filters []
Resources []
Inserts []
IV. Appendixes []
17. Troubleshooting []
Smarty/PHP errors [Smarty/PHP ]
18. Tips & Tricks []
Blank Variable Handling []
Default Variable Handling []
Passing variable title to header template []
Dates []
WAP/WML
Componentized Templates []
Obfuscating E-mail Addresses []
19. Resources []
20. BUGS []
21. LIST
Next
Preface
Smarty - the compiling PHP template engine
Smarty - PHP
Priv PHP Next
Preface[]
It is undoubtedly one of the most asked questions on the PHP mailing lists:
scripts independent of the layout? While PHP is billed as "HTML embedded scripting
writing a couple of projects that mixed PHP and HTML freely one comes up with the id
separation of form and content is a Good Thing [TM]. In addition, in many companies
layout designer and programmer are separate. Consequently, the search for a templa
ensues.
PHP PHP PHP
In our company for example, the development of an application goes on as
requirements docs are done, the interface designer makes mockups of the interface a
to the programmer. The programmer implements business logic in PHP and uses inte
to create skeleton templates. The project is then handed off to the HTML designer/we
person who brings the templates up to their full glory. The project may go back
programming/HTML a couple of times. Thus, it's important to have good template sup
programmers don't want anything to do with HTML and don't want HTML designers m
with PHP code. Designers need support for config files, dynamic blocks and other inte
but they don't want to have to deal with intricacies of the PHP programming language
,,[],PHP,htmlhtmlphpphp
Looking at many templating solutions available for PHP today, most of them
way of substituting variables into templates and do a limited form of dynamic block fun
our needs required a bit more than that. We didn't want programmers to be dealing w
at ALL, but this was almost inevitable. For instance, if a designer wanted background
alternate on dynamic blocks, this had to be worked out with the programmer in
needed designers to be able to use their own configuration files, and pull variables fro
templates. The list goes on.
php,phphtml:,
We started out writing out a spec for a template engine back in late 1999.
began to work on a template engine written in C that would hopefully be accepted for
PHP. Not only did we run into many complicated technical barriers, but there was also
debate about exactly what a template engine should and should not do. From this
decided that the template engine should be written in PHP as a class, for anyone to u
fit. So we wrote an engine that did just that and SmartTemplate came into existence (n
was never submitted to the public). It was a class that did almost everything we wante
variable substitution, supported including other templates, integration with config files,
Prev PHP Home Next
PHP code, limited 'if' statement functionality and much more robust dynamic blocks w
Getting Started
multiply nested. It did all this with regular expressions and the code turned
Smarty - the compiling PHP
say, impenetrable. It was also noticably slow in large applications from all the parsing
template engine
Getting Started[
expression work it had to do on each invocation. The biggest problem from a program
[Smarty - PHP ]
]
view was all the necessary work in the PHP script to setup and process templates and
blocks. How do we make this easier?
1999,,cphp
'if'
Then came the vision of what ultimately became Smarty. We know how fast PHP
overhead of template parsing. We also know how meticulous and overbearing the PH
may look to the average designer, and this could be masked with a much simpler tem
So what if we combined the two strengths? Thus, Smarty was born...
smartyphpphp""
Smarty......
Smarty - the compiling PHP template engine
Prev PHP Next
I. Getting Started
Table of Contents
1. What is Smarty? smaty?
2. Installation
Plugin architecture
Smarty.class.php
Smarty_Compiler.class.php
Config_File.class.php
debug.tpl
/core/*.php (all of them)
/plugins/*.php (all of them)
require('Smarty.class.php');
$smarty = new Smarty;
Try running the above script. If you get an error saying the
Smarty.class.php file could not be found, you have to do one of the
following:
," Smarty.class.php " ,:
require('/usr/local/lib/php/Smarty/Smarty.class.php');
$smarty = new Smarty;
define('SMARTY_DIR','/usr/local/lib/php/Smarty/');
require(SMARTY_DIR.'Smarty.class.php');
$smarty = new Smarty;
Now that the library files are in place, it's time to setup the Smarty
directories for your application. Smarty requires four directories which are
(by default) named templates , templates_c , configs and cache . Each of
these are definable by the Smarty class properties $template_dir ,
$compile_dir , $config_dir , and $cache_dir respectively. It is highly
recommended that you setup a separate set of these directories for each
application that will use Smarty.
,SmartySmarty4,:
Smarty: $template_dir, $compile_dir, $config_dir, and $cache_dir
respectivelysmarty!
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 outside of the
document root.
web,:"/web/www.mydomain.com/docs/"Smarty4
/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/core/*.php
/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
We need to create the index.tpl file that Smarty will load. This will be
located in your $template_dir.
index.tplsmarty. $template_dir
{* Smarty *}
Hello, {$name}!
$smarty->template_dir = '/web/www.mydomain.com/smarty/guestbook
$smarty->compile_dir = '/web/www.mydomain.com/smarty/guestbook/
$smarty->config_dir = '/web/www.mydomain.com/smarty/guestbook/c
$smarty->cache_dir = '/web/www.mydomain.com/smarty/guestbook/ca
$smarty->assign('name','Ned');
$smarty->display('index.tpl');
Now load the index.php file from your web browser. You should see
"Hello, Ned!"
index.php,"Hello, Porky!"
You have completed the basic setup for Smarty!
Smarty,!!
function Smarty_GuestBook() {
// Class Constructor. These automatically get
//.
$this->Smarty();
$this->template_dir = '/web/www.mydomain.com/sm
$this->compile_dir = '/web/www.mydomain.com/sma
$this->config_dir = '/web/www.mydomain.com/smar
$this->cache_dir = '/web/www.mydomain.com/smart
$this->caching = true;
$this->assign('app_name','Guest Book');
}
require('guestbook/setup.php');
$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.
smarty.Smarty_GuestBook,^_^
Table of Contents[]
3. Basic Syntax []
4. Variables []
5. Variable Modifiers []
6. Combining Modifiers []
7. Built-in Functions []
8. Custom Functions []
9. Config Files []
10. Debugging Console []
All Smarty template tags are enclosed within delimiters. By default, these
delimiters are { and }, but they can be changed.
smarty.
{ },.
For these examples, we will assume that you are using the default
delimiters. In Smarty, all content outside of delimiters is displayed as
static content, or unchanged. When Smarty encounters template tags, it
attempts to interpret them, and displays the appropriate output in their
place.
,.
smarty,,.
smarty,, .
Comments[]
Template comments are surrounded by asterisks, and that is surrounded
by the delimiter tags like so: {* this is a comment *} Smarty comments are
not displayed in the final output of the template. They are used for
making internal notes in the templates.
*, {* this is a comment *}
smarty.
.
{* Smarty *}
{include file=$includeFile}
{include file=#includeFile#}
Each Smarty tag either prints a variable or invokes some sort of function.
Functions are processed and displayed by enclosing the function and its
attributes into delimiters like so: {funcname attr1="val" attr2="val"}.
smarty.
'{'.:
{funcname attr1="val" attr2="val"}.
{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"}
Both built-in functions and custom functions have the same syntax in the
templates. Built-in functions are the inner workings of Smarty, such as {if}
, {section} and {strip} . They cannot be modified. Custom functions are
additional functions implemented via plugins. They can be modified to
your liking, or you can add new ones. {html_options} and
{html_select_date} are examples of custom functions.
.
smarty, {if} , {section} and {strip} ..
,. ,..
{html_options} {html_select_date}
--------------------------------------------------------------------------------
{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>
SYNTAX EXAMPLES:
{func var="test $foo test"} <-- sees $foo
{func var="test $foo_bar test"} <-- sees $foo_bar
{func var="test $foo[0] test"} <-- sees $foo[0]
{func var="test $foo[bar] test"} <-- sees $foo[bar]
{func var="test $foo.bar test"} <-- sees $foo (not $foo.bar)
{func var="test `$foo.bar` test"} <-- sees $foo.bar
PRACTICAL EXAMPLES:
{include file="subdir/$tpl_name.tpl"} <-- will replace $tpl_na
{cycle values="one,two,`$smarty.config.myval`"} <-- must have
Attributes Math
Up
[] []
Smarty - the compiling PHP template engine
Prev PHP Chapter 3. Basic Syntax[3.] Next
Math[]
Math can be applied directly to variable values.
{$foo+1}
{$foo*$bar}
{* some more complicated examples *}
{$foo->bar-$bar[1]*$baz->foo->bar()-3*7}
{if ($foo+$bar.test%$baz*134232+10+$b+10)}
{$foo|truncate:"`$fooTruncCount/$barTruncFactor-1`"}
Embedding Vars in
Variables
Double Quotes Up
[]
[ ]
Smarty - the compiling PHP template engine
Prev PHP Next
Chapter 4. Variables[.] .
Table of Contents[]
Variables assigned from PHP[PHP]
Variables loaded from config files[]
{$smarty} reserved variable[{$smarty} ]
Smartymodifiers,.
,.:
{$Name}
{$Contacts[row].Phone}
<body bgcolor="{#bgcolor#}">
Variables assigned from PHP
PHP
Table of Contents[]
Associative arrays[]
Array indexes[]
Objects[]
Variables that are assigned from PHP are referenced by preceding them
with a dollar sign $.
Variables assigned from within the template with the assign function are
also displayed this way.
PHP"$".php
assign.$
index.php:
index.tpl:
OUTPUT:
foo.conf:
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="{$sma
<tr bgcolor="{$smarty.config.rowBgColor}">
<td>First</td>
<td>Last</td>
<td>Address</td>
</tr>
</table>
</body>
</html>
<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 file variables cannot be used until after they are loaded in from a
config file. This procedure is explained later in this document under
{config_load} .
.
{config_load} . .
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|capitalize}
OUTPUT:
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|count_characters}
{$articleTitle|count_characters:true}
OUTPUT:
index.php:
index.tpl:
{$articleTitle|cat:" yesterday."}
OUTPUT:
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|count_paragraphs}
OUTPUT:
War Dims Hope for Peace. Child's Death Ruins Couple's Holiday.
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|count_sentences}
OUTPUT:
Two Soviet Ships Collide - One Dies. Enraged Cow Injures Farme
2
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|count_words}
OUTPUT:
This is the
default date if
2 string No n/a the input is
empty.
This formats a date and time into the given strftime() format.
Dates can be passed to Smarty as unix timestamps, mysql timestamps or
any string made up of month day year (parsable by strtotime).
Designers can then use date_format to have complete control of the
formatting of the date.
If the date passed to date_format is empty and a second parameter is
passed, that will be used as the date to format.
strftime()
Unixmysql(parsable by strtotime)smarty
date_format
date_format,
index.php:
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
%h - same as %b
%n - newline character
%t - tab character
:date_formatphpstrftime()
phpstrftime()
.
This is used to set a default value for a variable. If the variable is empty
or unset, the given default value is printed instead. Default takes one
argument.
index.php:
index.tpl:
{$articleTitle|default:"no title"}
{$myTitle|default:"no title"}
OUTPUT:
1 string No html,htmlall,url,quotes,hex,hexentity,javascript
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|escape}
{$articleTitle|escape:"html"} {* escapes & " ' < > *}
{$articleTitle|escape:"htmlall"} {* escapes ALL html entities
{$articleTitle|escape:"url"}
{$articleTitle|escape:"quotes"}
<a href="mailto:{$EmailAddress|escape:"hex"}">{$EmailAddress|e
OUTPUT:
This is the
character
2 string No (one space) used to
indent with.
HTML& n b s p;()
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|indent}
{$articleTitle|indent:10}
{$articleTitle|indent:1:"\t"}
OUTPUT:
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|lower}
OUTPUT:
index.php:
index.tpl:
{$articleTitle|nl2br}
OUTPUT:
This is the
regular
1 string Yes n/a expression to
be replaced.
.
This is the
string of text
2 string Yes n/a to replace
with.
A regular expression search and replace on a variable. Use the syntax for
preg_replace() from the PHP manual.
.
Phppreg_replace().
index.php:
index.tpl:
{* replace each carriage return, tab & new line with a space *
{* ,tab, *}
{$articleTitle}
{$articleTitle|regex_replace:"/[\r\t\n]/":" "}
OUTPUT:
Infertility unlikely to
be passed on, experts say.
Infertility unlikely to be passed on, experts say.
This is the
string of text
2 string Yes n/a to replace
with.
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|replace:"Garden":"Vineyard"}
{$articleTitle|replace:" ":" "}
OUTPUT:
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|spacify}
{$articleTitle|spacify:"^^"}
OUTPUT:
This is a way to format strings, such as decimal numbers and such. Use
the syntax for sprintf for the formatting.
..sprintf
index.php:
index.tpl:
{$number}
{$number|string_format:"%.2f"}
{$number|string_format:"%d"}
OUTPUT:
23.5787446
23.58
24
Note: If you want to strip blocks of template text, use the strip
function.
:, strip
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|strip}
{$articleTitle|strip:" "}
OUTPUT:
Grandmother of
eight makes hole in one.
Grandmother of eight makes hole in one.
Grandmother of eight makes hole in&nb
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|strip_tags}
OUTPUT:
This is the
text to
append if
2 string No ...
truncation
occurs.
This
determines
whether or
not to
truncate at a
word
3 boolean No false
boundary
(false), or at
the exact
character
(true).
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|truncate}
{$articleTitle|truncate:30}
{$articleTitle|truncate:30:""}
{$articleTitle|truncate:30:"---"}
{$articleTitle|truncate:30:"":true}
{$articleTitle|truncate:30:"...":true}
OUTPUT:
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|upper}
OUTPUT:
This
determines
whether or
not to wrap at
a word
3 boolean No false boundary
(false), or at
the exact
character
(true).
index.php:
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.
index.php:
index.tpl:
{$articleTitle}
{$articleTitle|upper|spacify}
{$articleTitle|lower|spacify|truncate}
{$articleTitle|lower|truncate:30|spacify}
{$articleTitle|lower|spacify|truncate:30:". . ."}
OUTPUT:
Caution
{insert} . {insert}
scope=parent.
global boolean No No : scope
scope
This function is used for loading in variables from a configuration file into
the template. See Config Files for more info.
. .
Example 7-2. function config_load
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>
Config files may also contain sections. You can load variables from within
a section with the added attribute section .
section .
NOTE: Config file sections and the built-in template function called
section have nothing to do with each other, they just happen to share a
common naming convention.
section section
<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>
Attribute
Type Required Default Description
Name
The name of
the array you
from string Yes n/a
are looping
through
The name of
the variable
item string Yes n/a that is the
current
element
The name of
the variable
key string No n/a
that is the
current key
The name of
the foreach
loop for
name string No n/a
accessing
foreach
properties
{* this example will print out all the values of the $custid ar
{* $custid *}
{foreach from=$custid item=curr_id}
id: {$curr_id}<br>
{/foreach}
OUTPUT:
id: 1000<br>
id: 1001<br>
id: 1002<br>
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 foreach name .
Include tags are used for including other templates in the current
template. Any variables available in the current template are also
available within the included template. The include tag must have the
attribute "file", which contains the template resource path.
Include . . file .
You can optionally pass the assign attribute, which will specify a template
variable name that the output of include will be assigned to instead of
displayed.
assign
{include file="footer.tpl"}
Use the syntax for template resources to include files outside of the
$template_dir directory.
$template_dir .
{* absolute filepath *}
{include file="/usr/local/include/templates/header.tpl"}
load_nav.php
-------------
<?php
index.tpl
---------
Insert tags work much like include tags, except that insert tags are not
cached when you have template caching enabled. They will be executed
on every invocation of the template.
Insert inluce insert .
Let's say you have a template with a banner slot at the top of the page.
The banner can contain any mixture of HTML, images, flash, etc. so we
can't just use a static link here, and we don't want this contents cached
with the page. In comes the insert tag: the template knows
#banner_location_id# and #site_id# values (gathered from a config file),
and needs to call a function to get the banner contents.
HTMLFLASH. .
#site_id# ().
In this example, we are using the name "getBanner" and passing the
parameters #banner_location_id# and #site_id#. Smarty will look for a
function named insert_getBanner() in your PHP application, passing the
values of #banner_location_id# and #site_id# as the first argument in an
associative array. All insert function names in your application must be
prepended with "insert_" to remedy possible function name-space
conflicts. Your insert_getBanner() function should do something with the
passed values and return the results. These results are then displayed in
the template in place of the insert tag. In this example, Smarty would call
this function: insert_getBanner(array("lid" => "12345","sid" => "67890"));
and display the returned results in place of the insert tag.
getBanner name #banner_location_id# #site_id# .
Smarty php insert_getBanner() #banner_location_id#
#site_id# . insert insert_ . insert_getBanner()
Smarty insert_getBanner(array("lid"=>"12345","sid"=>67890"));.
If you supply the "assign" attribute, the output of the insert tag will be
assigned to this template variable instead of being output to the template.
NOTE: assigning the output to a template variable isn't too useful with
caching enabled.
assign ..
If you supply the "script" attribute, this php script will be included (only
once) before the insert function is executed. This is the case where the
insert function may not exist yet, and a php script must be included first to
make it work. The path can be either absolute, or relative to $trusted_dir.
When security is enabled, the script must reside in $trusted_dir.
script ()script php .
The Smarty object is passed as the second argument. This way you can
reference and modify information in the Smarty object from within the
insert function.
Smart $this smarty .
{* same as above *}
{if $name == "Fred" || $name == "Wilma"}
...
{/if}
OUTPUT:
{literal}
<script language=javascript>
<!--
function isblank(field) {
if (field.value == '')
{ return false; }
else
{
document.loginform.submit();
return true;
}
}
// -->
</script>
{/literal}
{php}
// including a php script directly
// from the template.
include("/path/to/display_weather.php");
{/php}
Attribute
Type Required Default Description
Name
The name of
name string Yes n/a
the section
The name of
the variable
loop [$variable_name] Yes n/a to determine
# of loop
iterations
The index
position that
the section
will begin
looping. If the
value is
negative, the
start position
is calculated
from the end
of the array.
For example,
if there are
seven values
start integer No 0 in the loop
array and
start is -2, the
start index is
5. Invalid
values
(values
outside of the
length of the
loop array)
are
automatically
truncated to
the closest
valid value.
The step
value that will
be used to
traverse the
loop array.
For example,
step=2 will
step integer No 1 loop on index
0,2,4, etc. If
step is
negative, it
will step
through the
array
backwards.
Sets the
maximum
number of
max integer No 1
times the
section will
loop.
determines
whether or
show boolean No true not to show
this section
Template sections are used for looping over arrays of data. All section
tags must be paired with /section tags. Required parameters are name
and loop . The name of the section can be anything you like, made up of
letters, numbers and underscores. Sections can be nested, and the
nested section names must be unique from each other. The loop variable
(usually an array of values) determines the number of times the section
will loop. When printing a variable within a section, the section name
must be given next to variable name within brackets []. sectionelse is
executed when there are no values in the loop variable.
section . section . name loop . . name .
loop (). section name .
{* this example will print out all the values of the $custid a
{section name=customer loop=$custid}
id: {$custid[customer]}<br>
{/section}
OUTPUT:
id: 1000<br>
id: 1001<br>
id: 1002<br>
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>
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>
OUTPUT:
Sections also have their own variables that handle section properties.
These are indicated like so: {$smarty.section.sectionname.varname}
Section . {$smarty.section.sectionname.varname}.
NOTE: As of Smarty 1.5.0, the syntax for section property variables has
been changed from {%sectionname.varname%} to
{$smarty.section.sectionname.varname}. The old syntax is still supported,
but you will only see reference to the new syntax in the manual
examples.
Smarty 1.5.0 section {%sectionname.varname%}
{$smarty.section.sectionname.varname}.
{* the following will be all run into one line upon output *}
{strip}
<table border=0>
<tr>
<td>
<A HREF="{$url}">
<font color="red">This is a test</font
</A>
</td>
</tr>
</table>
{/strip}
OUTPUT:
Notice that in the above example, all the lines begin and end with HTML
tags. Be aware that all the lines are run together. If you have plain text at
the beginning or end of any line, they will be run together, and may not be
desired results.
HTML. . .
Smarty comes with several custom functions that you can use in the
templates.
Smarty .
assign
Attribute
Type Required Default Description
Name
The name of
the variable
var string Yes n/a
being
assigned
The value
value string Yes n/a being
assigned
OUTPUT:
counter is used to print out a count. counter will remember the count on
each iteration. You can adjust the number, the interval and the direction
of the count, as well as determine whether or not to print the value. You
can run multiple counters concurrently by supplying a unique name for
each one. If you do not supply a name, the name 'default' will be used.
counter . counter . interval direction .
"default" .
If you supply the special "assign" attribute, the output of the counter
function will be assigned to this template variable instead of being output
to the template.
"assign" assign .
{counter}<br>
{counter}<br>
{counter}<br>
{counter}<br>
OUTPUT:
2<br>
4<br>
6<br>
8<br>
OUTPUT:
<tr bgcolor="#eeeeee">
<td>1</td>
</tr>
<tr bgcolor="#d0d0d0">
<td>2</td>
</tr>
<tr bgcolor="#eeeeee">
<td>3</td>
</tr>
html
output string No html
javascript
{debug} dumps the debug console to the page. This works regardless of
the debug settings in Smarty. Since this gets executed at runtime, this is
only able to show the assigned variables, not the templates that are in
use. But, you see all the currently available variables within the scope of
this template.
{debug} . Smarty debug . . .
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:
fetch is used to fetch files from the local file system, http, or ftp and
display the contents. If the file name begins with "http://", the web site
page will be fetched and displayed. If the file name begins with "ftp://",
the file will be fetched from the ftp server and displayed. For local files,
the full system file path must be given, or a path relative to the executed
php script.
fetch HTTPFTP. "http://".
If you supply the special "assign" attribute, the output of the fetch function
will be assigned to this template variable instead of being output to the
template. (new in Smarty 1.5.0)
"assign" assign .(Smarty
Yes,
output array n/a
options
selected string/array No empty
associative Yes, values
options n/a
array
separator string No empty
labels boolean No true <label>
index.php:
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('cust_ids', array(1000,1001,1002,1003));
$smarty->assign('cust_names', array('Joe Schmoe','Jack Smith','
$smarty->assign('customer_id', 1001);
$smarty->display('index.tpl');
index.tpl:
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('cust_checkboxes', array(
1000 => 'Joe Schmoe',
1001 => 'Jack Smith',
1002 => 'Jane Johnson',
1003 => 'Charlie Brown'));
$smarty->assign('customer_id', 1001);
$smarty->display('index.tpl');
index.tpl:
index.php:
require('Smarty.class.php');
$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" alt="" border="0" width="44" height="68
<img src="/path/from/docroot/pumpkin.jpg" alt="" border="0" wi
<img src="../path/relative/to/currdir/pumpkin.jpg" alt="" bord
Yes, unless
values array using options n/a
attribute
Yes, unless
output array using options n/a
attribute
selected string/array No empty
Yes, unless
associative
options using values n/a
array
and output
name string No empty
html_options is a custom function that creates html option group with
provided data. It takes care of which item(s) are selected by default as
well. Required attributes are values and output, unless you use options
instead.
html_options . . values ouput
If a given value is an array, it will treat it as an html OPTGROUP, and
display the groups. Recursion is supported with OPTGROUP. All output
is XHTML compatible.
OPTGROUP . XHTML .
If the optional name attribute is given, the <select name="groupname">
</select> tags will enclose the option list. Otherwise only the option list is
generated.
name<select name="groupname"></select>. .
All parameters that are not in the list above are printed as name/value-
pairs inside the <select>-tag. They are ignored if the optional name is not
given.
<select> "/". name .
index.php:
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('cust_ids', array(1000,1001,1002,1003));
$smarty->assign('cust_names', array('Joe Schmoe','Jack Smith','
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 ou
</select>
index.php:
require('Smarty.class.php');
$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
</select>
<select name=customer_id>
<option value="1000">Joe Schmoe</option>
<option value="1001" selected="selected">Jack Smith</o
<option value="1002">Jane Johnson</option>
<option value="1003">Charlie Brown</option>
</select>
html_radios is a custom function that creates html radio button group with
provided data. It takes care of which item is selected by default as well.
Required attributes are values and output, unless you use options
instead. All output is XHTML compatible.
html_radios . . values ouput
XHTML .
All parameters that are not in the list above are printed as name/value-
pairs inside each of the created <input>-tags.
<input> "/".
index.php:
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('cust_ids', array(1000,1001,1002,1003));
$smarty->assign('cust_names', array('Joe Schmoe','Jack Smith','
Johnson','Carlie Brown'));
$smarty->assign('customer_id', 1001);
$smarty->display('index.tpl');
index.tpl:
index.php:
require('Smarty.class.php');
$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_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>
{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>
index.php:
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('data',array(1,2,3,4,5,6,7,8,9));
$smarty->assign('tr',array('bgcolor="#eeeeee"','bgcolor="#ddddd
$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> </td><td> </td><td> </td></t
</table>
<table border="1">
<tr bgcolor="#eeeeee"><td>1</td><td>2</td><td>3</td><td>4</td>
<tr bgcolor="#dddddd"><td>5</td><td>6</td><td>7</td><td>8</td>
<tr bgcolor="#eeeeee"><td>9</td><td> </td><td> </td>
</table>
{* $height=4, $width=5 *}
OUTPUT:
OUTPUT:
100
OUTPUT:
OUTPUT:
9.44
{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
{mailto address="me@domain.com" extra='class="email"'}
OUTPUT:
. 1: bgcolor
bgbackground url to image No n/a "". 2:
Netscape
.
closetext string No n/a
noclose boolean No n/a
status string No n/a
autostatus boolean No n/a . : status
. : status
autostatuscap string No n/a
autostatus
overLibol_text
inarray integer No n/a
text. text
overLibol_caps
caparray integer No n/a caption.
{* create a link with a popup window when you move your mouse o
<A href="mypage.html" {popup text="This link takes you to my pa
{textformat wrap=40}
This is foo.
This is foo.
This is foo.
This is foo.
This is foo.
This is foo.
This is bar.
{/textformat}
OUTPUT:
This is bar.
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 bar.
This is foo.
This is foo.
This is foo.
This is foo.
This is foo.
This is foo.
This is bar.
{/textformat}
OUTPUT:
This is bar.
{textformat style="email"}
This is foo.
This is foo.
This is foo.
This is foo.
This is foo.
This is foo.
This is bar.
OUTPUT:
This is foo. This is foo. This is foo. This is foo. This is foo
foo.
This is bar.
bar foo bar foo foo. bar foo bar foo foo. bar foo bar foo foo.
bar foo foo. bar foo bar foo foo. bar foo bar foo foo. bar foo
foo.
# global variables
pageTitle = "Main Menu"
bodyBgColor = #000000
tableBgColor = #000000
rowBgColor = #00ff00
[Customer]
pageTitle = "Customer Info"
[Login]
pageTitle = "Login"
focus = "username"
Intro = """This is a value that spans more
than one line. you must enclose
it in triple quotes."""
# hidden section
[.Database]
host=my.domain.com
db=ADDRESSBOOK
user=php-user
pass=foobar
Values of config file variables can be in quotes, but not necessary. You
can use either single or double quotes. If you have a value that spans
more than one line, enclose the entire value with triple quotes ("""). You
can put comments into config files by any syntax that is not a valid config
file syntax. We recommend using a # (hash) at the beginning of the line.
(""")
This config file example has two sections. Section names are enclosed in
brackets []. Section names can be arbitrary strings not containing [ or ]
symbols. The four variables at the top are global variables, or variables
not within a section. These variables are always loaded from the config
file. If a particular section is loaded, then the global variables and the
variables from that section are also loaded. If a variable exists both as a
global and in a section, the section variable is used. If you name two
variables the same within a section, the last one will be used.
“[]”“[”“]”
Config files are loaded into templates with the built-in function
{config_load} .
{ config load }
You can hide variables or entire sections by prepending the variable
name or section name with a period. This is useful if your application
reads the config files and gets sensitive data from them that the template
engine does not need. If you have third parties doing template editing,
you can be certain that they cannot read sensitive data from the config
file by loading it into the template.
Technical Note: The debugging console does not work when you
use the fetch() API, only when using display(). It is a set of javascript
statements added to the very bottom of the generated template. If
you do not like javascript, you can edit the debug.tpl template to
format the output however you like. Debug data is not cached and
debug.tpl info is not included in the output of the debug console.
fetch() API display() javascript
debug.tpl debug.tpl
Note: The load times of each template and config file are in
seconds, or fractions thereof.
Prev PHP Home Next
Smarty For
Config Files Up
Programmers
Smarty - the compiling PHP template engine
Prev PHP Next
III. Smarty For Programmers
Table of Contents []
11. Constants
[]
12. Variables
[]
13. Methods
[]
14. Caching
[]
15. Advanced Features
[]
16. Extending Smarty With Plugins [Smarty]
SMARTY_DIR [Smarty]
SMARTY_DIR
Smarty
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.
SmartySmartySmarty,
require_once(SMARTY_DIR."Smarty.class.php");
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.
“./templates”php
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.
“./templates_c”php
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.
“./configs”php
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.
SmartySMARTY“plugins”SmartySMARTYphp
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.
debug.tplSmarty
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.
Smarty,..
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.,,.:
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.
PHP,Smarty ,.,.,.true.(),.,$compile_check"false".:
"false",,,.,,.
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.
Smarty.,0,.,...12.1Smarty
cache_lifetime..
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.
,(),.,.
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.
.,:"./cache",php.,.
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.)
(),,.,$caching$cache_lifetime"true".-1,.0(, $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.
,., clear_all_cache() , clear_cache() ().
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_dir.: cache handler function section
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.
,SmartyIf-Modified-Since.,"304 Not Modified",. {insert} .
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.
,.,.,,.,.
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.
,mac dos (\r and \r\n)\n.
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.
PHP_HANDLING - .,$php_handling.
IF_FUNCS - This is an array of the names of permitted PHP
functions in IF statements.
IF_FUNCS - ifphp.
INCLUDE_ANY - true/false. If set to true, any template can be
included from the file system, regardless of the $secure_dir list.
INCLUDE_ANY - .,,$secure_dir.
PHP_TAGS - true/false. If set to true, {php}{/php} tags are permitted
in the templates.
PHP_TAGS - .,{php}{/php}.
MODIFIER_FUNCS - This is an array of the names of permitted
PHP functions used as variable modifiers.
MODIFIER_FUNCS - php.
This is the left delimiter used by the template language. Default is "{".
,"{".
This is the right delimiter used by the template language. Default is "}".
,"}".
Specifies the name of the compiler class that Smarty will use to compile
the templates. The default is 'Smarty_Compiler'. For advanced users
only.Smarty.:'Smarty_Compiler'..
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.
phpSmarty,.,.
This tells smarty what resource type to use implicitly. The default value is
'file', meaning that $smarty->display('index.tpl'); and $smarty-
Prev PHP Home Next
>display('file:index.tpl'); are identical in meaning. See the resource chapter
$default_modifiers[]
for details. Up []Methods
smarty.'file',,$smarty->display('index.tpl');and
>display('file:index.tpl');. resource
Smarty - the compiling PHP template engine
Prev PHP Next
Chapter 13. Methods 13.
Table of Contents
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)
This is used to assign values to the templates. You can explicitly pass
name/value pairs, or associative arrays containing the name/value pairs.
/ /
void clear_all_assign ()
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.
“expire time”
This clears the value of an assigned variable. This can be a single value,
or an array of values.
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.
Fwolf:templates_c
This loads config file data and assigns it to the template. This works
identical to the template config_load function.
config_load
// load a section
//
$smarty->config_load('my.conf','foobar');
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().
$template_dir$compile_dir$template_dir
display() $compile_id
include("Smarty.class.php");
$smarty = new Smarty;
$smarty->caching = true;
$smarty->assign("Name","Fred");
$smarty->assign("Address",$address);
$smarty->assign($db_data);
Use the syntax for template resources to display files outside of the
$template_dir directory.
$template_dir
// absolute filepath
//
$smarty->display("/usr/local/include/templates/header.tpl");
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.
HTML
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().
$template_dir$compile_dir$template_dir
display() $compile_id
include("Smarty.class.php");
$smarty = new Smarty;
$smarty->caching = true;
$smarty->assign("Name","Fred");
$smarty->assign("Address",$address);
$smarty->assign($db_data);
echo $output;
This returns true if there is a valid cache for this template. This only
works if caching is set to true.
$smarty->caching = true;
if(!$smarty->is_cached("index.tpl")) {
// do database calls, assign vars here
//
}
$smarty->display("index.tpl");
$smarty->caching = true;
if(!$smarty->is_cached("index.tpl","FrontPage")) {
// do database calls, assign vars here
}
$smarty->display("index.tpl","FrontPage");
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'.
“pre”“post”“output” “trim”
/* PHP */
$smarty->register_block("translate", "do_translation");
{* template *}
{translate lang="br"}
Hello, world!
{/translate}
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.
array(&$object, $method)&$object$methodarray(&$ class,
$method)$class$method
$cacheable can be omitted in most cases. See Controlling Cacheability of
Plugins' Output on how to it properly.
$cacheable
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.
array(&$object, $method)&$object$methodarray(&$ class,
$method)$class$method
$cacheable and $cache_attrs can be omitted in most cases. See
Controlling Cacheability of Plugins' Output on how to use them properly.
$cacheable $cache_attrs
$smarty->register_function("date_now", "print_current_date");
// {date_now}
// {date_now format="%Y/%m/%d"}
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.
array(&$object, $method)&$object$methodarray(&$ class,
$method)$class$method
$smarty->register_modifier("sslash","stripslashes");
$smarty->register_resource("db", array("db_get_template",
"db_get_timestamp",
"db_get_secure",
"db_get_trusted"));
Prev PHP Home Next
register_prefilter trigger_error
Up
Smarty - the compiling PHP template engine
Prev PHP Chapter 13. Methods Next
trigger_error
This function checks whether the specified template exists. It can accept
either a path to the template on the filesystem or a resource string
specifying the template.
template
Use this to dynamically unregister block function plugin. Pass in the block
function name.
$smarty->unregister_function("fetch");
$smarty->unregister_modifier("strip_tags");
$smarty->unregister_resource("db");
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
$smarty->display('index.tpl');
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!
$chche_dir.phpphp
require('Smarty.class.php');
$smarty = new Smarty;
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
$smarty->compile_check = true;
$smarty->display('index.tpl');
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.
insert insert
You can clear all the cache files with the clear_all_cache() function, or
individual cache files (or groups) with the clear_cache() function.
clear_all_cache() clear_cache()
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
$smarty->display('index.tpl');
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
$my_cache_id = $_GET['article_id'];
$smarty->display('index.tpl',$my_cache_id);
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().
clear_cache()nullcache_id
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
$smarty->display('index.tpl',"sports");
In this manner, you can "group" your caches together by giving them the
same cache_id.
cache_id
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
$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');
:cache_iddisplay('themes/blue/index.tpl'),"themes/blue"
cache_iddisplay('themes/blue/index.tpl','themes|blue')
clear_cache(null,'themes|blue')blue theme(...)
index.php:
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
$smarty->register_function('remaining', 'remaining_seconds', fa
if (!$smarty->is_cached('index.tpl')) {
// fetch $obj from db and assign...
$smarty->assign_by_ref('obj', $obj);
}
$smarty->display('index.tpl');
index.tpl:
The number of seconds till the endtime of $obj is reached changes on each display
cached. Since the endtime attribute is cached the object only has to be pulled from th
written to the cache but not on subsequent requests of the page.
$obj
index.php:
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
$smarty->display('index.tpl');
index.tpl:
{dynamic}
{/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.
“““”{dynamic}...{/dynamic}
Table of Contents
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.
SMARTYPHP,
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.
<?php
// the object
class My_Object() {
function meth1($params, &$smarty_obj) {
return "this is my meth1";
}
}
$smarty->display("index.tpl");
?>
TEMPLATE:
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.
PHP
SMARTY
<?php
// put this in your application
function remove_dw_comments($tpl_source, &$smarty)
{
return preg_replace("/<!--#.*-->/U","",$tpl_source);
}
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.
PHP load filter() $autoload filters SMARTY
<?php
// put this in your application
function add_header_comment($tpl_source, &$smarty)
{
return "<?php echo \"<!-- Created by Smarty! -->\n\" ?>\n".$t
}
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.
display() fetch()
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.
load filter() $autoload filters SMARTY
<?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%40$2', $tpl_output);
return $tpl_output;
}
<?php
/*
example usage:
include('Smarty.class.php');
include('mysql_cache_handler.php');
$smarty->display('index.tpl');
*/
switch ($action) {
case 'read':
// save cache to database
$results = mysql_query("select CacheCo
if(!$results) {
$smarty_obj->_trigger_error_ms
}
$row = mysql_fetch_array($results,MYSQ
if($use_gzip && function_exists("gzunc
$cache_contents = gzuncompress
} else {
$cache_contents = $row["CacheC
}
$return = $results;
break;
case 'write':
// save cache to database
if($use_gzip && function_exists("gzcom
// compress the contents for s
$contents = gzcompress($cache_
} else {
$contents = $cache_content;
}
$results = mysql_query("replace into C
'$Cach
'".add
");
if(!$results) {
$smarty_obj->_trigger_error_ms
}
$return = $results;
break;
case 'clear':
// clear cache info
if(empty($cache_id) && empty($compile_
// clear them all
$results = mysql_query("delete
} else {
$results = mysql_query("delete
}
if(!$results) {
$smarty_obj->_trigger_error_msg
}
$return = $results;
break;
default:
// error, unknown action
$smarty_obj->_trigger_error_msg("cache_
$return = false;
break;
}
mysql_close($link);
return $return;
}
?>
Table of Contents
Templates from $template_dir
Templates from any directory
Templates from other sources
Default template handler function
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.
Version 2.0 introduced the plugin architecture that is used for almost all
the customizable functionality of Smarty. This includes:
2.0Smarty
functions
modifiers
block functions
compiler functions
prefilters
postfilters
outputfilters
resources
inserts
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.
register_* API API
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.
Smarty
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.
/API
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.
Smarty
function
modifier
block
compiler
prefilter
postfilter
outputfilter
resource
insert
The plugin functions inside the plugin files must be named as follows:
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.
Smarty
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).
fetch()
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.
Smarty $smarty
<?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];
}
?>
<?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);
}
?>
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.
<?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);
}
?>
<?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 '';
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.
$params['start']extract($params)
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.
$smarty->_tag_stack var_dump()
<?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;
}
}
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.
——SmartyPHP
See also register_compiler_function(), unregister_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 "
}
?>
This function can be called from the template as:
The resulting PHP code in the compiled template would be something like this:
PHP
<php
echo 'index.tpl compiled at 2002-02-20 20:02';
?>
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.
PHP
<?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")', $so
}
?>
<?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())
return $compiled;
}
?>
/*
* 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}
'$1%40$2', $output);
}
<?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, &$s
{
// 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;
}
}
<?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' paramet
return;
}
$datetime = strftime($params['format']);
return $datetime;
}
?>
Smarty
Smarty: index.tpl4:'%blah'
Fatal error: Smarty: [in index.tpl line 28]: syntax error: mis
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.
Smartysmarty
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.
Smartyphp.
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.
phpphpif}{/if}
{section}{/section}{if}php
There may be times when you want to print a default value for an empty
variable instead of printing nothing, such as printing " " so that
table backgrounds work properly. Many would use an {if} statement to
handle this, but there is a shorthand way with Smarty, using the default
variable modifier.
' '[ HTML]{if}Smatry
{$title|default:" "}
Default Variable
Troubleshooting Handling
Up
[] []
Smarty - the compiling PHP template engine
Prev PHP Chapter 18. Tips & Tricks[] Next
Default Variable Handling
When the majority of your templates use the same headers and footers, it
is common to split those out into their own templates and include them.
But what if the header needs to have a different title, depending on what
page you are coming from? You can pass the title to the header when it
is included.
---
mainpage.tpl
------------
archives.tpl
------------
{config_load file="archive_page.conf"}
{include file="header.tpl" title=#archivePageTitle#}
{* template body goes here *}
{include file="footer.tpl"}
header.tpl
----------
<HTML>
<HEAD>
<TITLE>{$title|default:"BC News"}</TITLE>
</HEAD>
<BODY>
footer.tpl
----------
</BODY>
</HTML>
When the main page is drawn, the title of "Main Page" is passed to the
header.tpl, and will subsequently be used as the title. When the archives
page is drawn, the title will be "Archives". Notice in the archive example,
we are using a variable from the archives_page.conf file instead of a hard
coded variable. Also notice that "BC News" is printed if the $title variable
is not set, using the default variable modifier.
[main page]‘Main Page'[header.tpl][archives
‘Archives'[archives_page.conf][$title]‘BC
Default Variable
Dates
Handling Up
[]
[]
Smarty - the compiling PHP template engine
Prev PHP Chapter 18. Tips & Tricks[] Next
Dates
{$startDate|date_format}
OUTPUT:
Jan 4, 2001
{$startDate|date_format:"%Y/%m/%d"}
OUTPUT:
2001/01/04
$startDate = makeTimeStamp($startDate_Year,$startDate_Month,$st
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);
}
// your Smarty template _must_ begin with the insert tag examp
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://ww
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?
PHPSmarty
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.
{php}{/php}PHP
{* Smarty *}
{php}
{/php}
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.
Smarty 1.5.0{include_php ...}phpPHP include_php
load_ticker.php
---------------
<?php
// setup our function for fetching stock data
function fetch_ticker($symbol,&$ticker_name,&$ticker_pr
// put logic here that fetches $ticker_name
// and $ticker_price from some resource
}
index.tpl
---------
{* Smarty *}
{include_php file="load_ticker.php"}
Obfuscating E-mail
WAP/WML
Up Addresses
[WAP/WML]
[]
Smarty - the compiling PHP template engine
Prev PHP Chapter 18. Tips & Tricks[] Next
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.
HTMLjavascriptmaito
index.tpl
---------
Send inquiries to
{mailto address=$EmailAddress encode="javascript" subject="Hel
Componentized
Resources
Templates Up
[]
[]
Smarty - the compiling PHP template engine
Prev PHP Next
Chapter 19. Resources
.
Smarty's homepage is located at http://smarty.php.net/. You can join the
mailing list by sending an e-mail to smarty-general-
subscribe@lists.php.net. An archive of the mailing list can be viewed at
http://marc.theaimsgroup.com/?l=smarty&r=1&w=2
Smartyhttp://smarty.php.net/
smarty-general-subscribe@lists.php.net
http://marc.theaimsgroup.com/?l=smarty&r=1&w=2
PHPPHP
zhangyx@12365.sd.cn
kolinwebmaster@im22.uni.cc
libk libkhorse@sohu.com
huix huix22@hotmail.com
flyhan hanbd7@sina.com
bralf ab_blunt@yahoo.com.cn
yuguanglou yuguanglou@21cn.com
fwolf fwolf001@tom.com
gavinguo gavin@jqw.cn
cnhfyycnhfyy@126.com
webmaster@ehome.51.net
index.php:
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>
index.php:
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>
name: {$person->name}<br>
email: {$person->email}<br>
OUTPUT:
{$smarty.const._MY_CONST_VAL}
iteration []
Iteration always starts with 1 and is incremented by one one each
iteration.
iteration 1 1.[]
total .
Technical Note: If the step and start section properties are not
modified, then this works the same as the iteration section property,
except it starts on 0 instead of 1.
stepstartiteration0.
OUTPUT:
0 id: 1000<br>
1 id: 1001<br>
2 id: 1002<br>
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>
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>
OUTPUT:
<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>
<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>
OUTPUT:
1 id: 1000<br>
2 id: 1001<br>
3 id: 1002<br>
OUTPUT:
0 id: 1000<br>
1 id: 1001<br>
2 id: 1002<br>
{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>
OUTPUT:
0 id: 1000<br>
2 id: 1001<br>
4 id: 1002<br>
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.
Note: 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.
<?php
// put this function somewhere in your application