Built-in Functions

Smarty comes with several built-in functions. Built-in functions are integral to the template language. You cannot create custom functions with the same names, nor can you modify built-in functions.

capture

capture is used to collect the output of the template into a variable instead of displaying it. Any content between {capture name="foo"} and {/capture} is collected into the variable specified in the name attribute. The captured content can be used in the template from the special variable $smarty.capture.foo where foo is the value passed in the name attribute. If you do not supply a name attribute, then "default" will be used. All {capture} commands must be paired with {/capture}. You can nest capture commands. capture was added to Smarty 1.4.0. The "name" attribute was added to Smarty 1.4.5.

NOTE: Smarty 1.4.0 - 1.4.4 placed the captured content into the variable named $return. As of 1.4.5, this behavior was changed to use the name attribute, so update your templates accordingly.

Caution

Be careful when capturing {insert} output. If you have caching turned on and you have {insert} commands that you expect to run within cached content, do not capture this content.

Example 3-32. capturing template content

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

config_load

Attribute NameTypeRequiredDefaultDescription
filestringYesn/aThe name of the config file to include
sectionstringNon/aThe name of the section to load
scopestringnolocal How the scope of the loaded variables are treated, which must be one of local, parent or global. local means variables are loaded into the local template context. parent means variables are loaded into both the local context and the parent template that called it. global means variables are available to all templates. NOTE: This was added to Smarty 1.4.3.
globalbooleanNoNo Whether or not variables are visible to the parent template, same as scope=parent. NOTE: This attribute is deprecated by the scope attribute, but still supported. If scope is supplied, this value is ignored.

This function is used for loading in variables from a configuration file into the template. See Config Files for more info.

Example 3-33. function 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.

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.

Example 3-34. function config_load with section

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

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

include

Attribute NameTypeRequiredDefaultDescription
filestringYesn/aThe name of the template file to include
assignstringNon/aThe name of the variable that the output of include will be assigned to
[var ...][var type]Non/avariable to pass local to template

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.

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. This was added to Smarty 1.5.0.

Example 3-35. function include

{include file="header.tpl"}

{* body of template goes here *}

{include file="footer.tpl"}

You can also pass variables to included templates as attributes. Any variables explicitly passed to an included template as attributes are only available within the scope of the included file. Attribute variables override current template variables, in the case they are named alike.

Example 3-36. function include passing variables

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

{* body of template goes here *}

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

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

Example 3-37. function include template resource examples

{* absolute filepath *}
{include file="/usr/local/include/templates/header.tpl"}

{* absolute filepath (same thing) *}
{include file="file:/usr/local/include/templates/header.tpl"}

{* windows absolute filepath (MUST use "file:" prefix) *}
{include file="file:C:/www/pub/templates/header.tpl"}

{* include from template resource named "db" *}
{include file="db:header.tpl"}

include_php

Attribute NameTypeRequiredDefaultDescription
filestringYesn/aThe name of the php file to include
assignstringNon/aThe name of the variable that the output of include_php will be assigned to

include_php tags are used to include a php script in your template. If security is enabled, then the php script must be located in the $trusted_dir path. The include_php tag must have the attribute "file", which contains the path to the included php file, either relative to $trusted_dir, or an absolute path.

include_php is a nice way to handle componentized templates, and keep PHP code separate from the template files. Lets say you have a template that shows your site navigation, which is pulled dynamically from a database. You can keep your PHP logic that grabs database content in a separate directory, and include it at the top of the template. Now you can include this template anywhere without worrying if the database information was assigned by the application before hand.

You can optionally pass the assign attribute, which will specify a template variable name that the output of include_php will be assigned to instead of displayed.

include_php was added to Smarty 1.5.0.

Example 3-38. function include_php

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

<?php

	// load in variables from a mysql db and assign them to the template
	require_once("MySQL.class.php");
	$sql = new MySQL;
	$sql->query("select * from site_nav_sections order by name",SQL_ALL);
	$this->assign($sections,$sql->record);

?>


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

{* absolute path, or relative to $trusted_dir *}
{include_php file="/path/to/load_nav.php"}

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

insert

Attribute NameTypeRequiredDefaultDescription
namestringYesn/aThe name of the insert function (insert_name)
assignstringNon/aThe name of the template variable the output will be assigned to
scriptstringNon/aThe name of the php script that is included before the insert function is called
[var ...][var type]Non/avariable to pass to insert function

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.

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.

Example 3-39. function insert

{* example of fetching a banner *}
{insert name="getBanner" lid=#banner_location_id# sid=#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.

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. (added to Smarty 1.5.0)

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. (added to Smarty 1.5.2)

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. (added in 1.4.5)

Technical Note: It is possible to have portions of the template not cached. If you have caching turned on, insert tags will not be cached. They will run dynamically every time the page is created, even within cached pages. This works good for things like banners, polls, live weather, search results, user feedback areas, etc.

if,elseif,else

if statements in Smarty have much the same flexibility as php if statements, with a few added features for the template engine. Every if must be paired with an /if. else and elseif are also permitted. "eq", "ne","neq", "gt", "lt", "lte", "le", "gte" "ge","is even","is odd", "is not even","is not odd","not","mod","div by","even by","odd by","==","!=",">", "<","<=",">=" are all valid conditional qualifiers, and must be separated from surrounding elements by spaces.

Example 3-40. if statements

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

{* an example with "or" logic *}
{if $name eq "Fred" or $name eq "Wilma"}
	...
{/if}

{* same as above *}
{if $name == "Fred" || $name == "Wilma"}
	...
{/if}

{* the following syntax will NOT work, conditional qualifiers
   must be separated from surrounding elements by spaces *}
{if $name=="Fred" || $name=="Wilma"}
	...
{/if}


{* parenthesis are allowed *}
{if ( $amount < 0 or $amount > 1000 ) and $volume >= #minVolAmt#}
	...
{/if}

{* you can also embed php function calls *}
{if count($var) gt 0}
	...
{/if}

{* test if values are even or odd *}
{if $var is even}
	...
{/if}
{if $var is odd}
	...
{/if}
{if $var is not odd}
	...
{/if}

{* test if var is divisible by 4 *}
{if $var is div by 4}
	...
{/if}

{* test if var is even, grouped by two. i.e.,
0=even, 1=even, 2=odd, 3=odd, 4=even, 5=even, etc. *}
{if $var is even by 2}
	...
{/if}

{* 0=even, 1=even, 2=even, 3=odd, 4=odd, 5=odd, etc. *}
{if $var is even by 3}
	...
{/if}

ldelim,rdelim

ldelim and rdelim are used for displaying the literal delimiter, in our case "{" or "}". The template engine always tries to interpret delimiters, so this is the way around that.

Example 3-41. ldelim, rdelim

{* this will print literal delimiters out of the template *}

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


OUTPUT:

{funcname} is how functions look in Smarty!

literal

Literal tags allow a block of data to be taken literally, not being interpreted by the Smarty engine. This is handy for things like javascript sections, where there maybe curly braces and such things that would confuse the template parser. Anything within {literal}{/literal} tags is not interpreted, but displayed as-is.

Example 3-42. literal tags

{literal}
	<script language=javascript>

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

	</script>
{/literal}

php

php tags allow php to be embedded directly into the template. They will not be escaped, regardless of the $php_handling setting. This is for advanced users only, not normally needed. This was added to 1.4.0.

Example 3-43. php tags

{php}
		// including a php script directly
		// from the template.
		include("/path/to/display_weather.php");
{/php}

section,sectionelse

Attribute NameTypeRequiredDefaultDescription
namestringYesn/aThe name of the section
loop[$variable_name]Yesn/aThe name of the variable to determine # of loop iterations
startintegerNo0The 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 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. (Added to Smarty 1.4.4.)
stepintegerNo1The step value that will be used to traverse the loop array. For example, step=2 will loop on index 0,2,4, etc. If step is negative, it will step through the array backwards. (Added to Smarty 1.4.4.)
maxintegerNo1Sets the maximum number of times the section will loop. (Added to Smarty 1.4.4.)
showbooleanNotruedetermines whether or 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.

Example 3-44. section


{* this example will print out all the values of the $custid array *}
{section name=customer loop=$custid}
	id: {$custid[customer]}<br>
{/section}

OUTPUT:

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

Example 3-45. section loop variable

{* the loop variable only determines the number of times to loop.
   you can access any variable from the template within the section.
   This example assumes that $custid, $name and $address are all
   arrays containing the same number of values *}
{section name=customer loop=$custid}
	id: {$custid[customer]}<br>
	name: {$name[customer]}<br>
	address: {$address[customer]}<br>
	<p>
{/section}


OUTPUT:

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

Example 3-46. section names

{* the name of the section can be anything you like,
   and it is used to reference the data within the section *}
{section name=mydata loop=$custid}
	id: {$custid[mydata]}<br>
	name: {$name[mydata]}<br>
	address: {$address[mydata]}<br>
	<p>
{/section}

Example 3-47. nested sections

{* sections can be nested as deep as you like. With nested sections,
   you can access complex data structures, such as multi-dimensional
   arrays. In this example, $contact_type[customer] is an array of
   contact types for the current customer. *}
{section name=customer loop=$custid}
	id: {$custid[customer]}<br>
	name: {$name[customer]}<br>
	address: {$address[customer]}<br>
	{section name=contact loop=$contact_type[customer]}
		{$contact_type[customer][contact]}: {$contact_info[customer][contact]}<br>
	{/section}
	<p>
{/section}


OUTPUT:

id: 1000<br>
name: John Smith<br>
address: 253 N 45th<br>
home phone: 555-555-5555<br>
cell phone: 555-555-5555<br>
e-mail: [email protected]<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: [email protected]<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: [email protected]<br>
<p>

Example 3-48. sections and associative arrays

{* This is an example of printing an associative array
   of data within a section *}
{section name=customer loop=$contacts}
	name: {$contacts[customer].name}<br>
	home: {$contacts[customer].home}<br>
	cell: {$contacts[customer].cell}<br>
	e-mail: {$contacts[customer].email}<p>
{/section}


OUTPUT:

name: John Smith<br>
home: 555-555-5555<br>
cell: 555-555-5555<br>
e-mail: [email protected]<p>
name: Jack Jones<br>
home phone: 555-555-5555<br>
cell phone: 555-555-5555<br>
e-mail: [email protected]<p>
name: Jane Munson<br>
home phone: 555-555-5555<br>
cell phone: 555-555-5555<br>
e-mail: [email protected]<p>

Example 3-49. sectionelse

{* sectionelse will execute if there are no $custid values *}
{section name=customer loop=$custid}
	id: {$custid[customer]}<br>
{sectionelse}
	there are no values in $custid.
{/section}

Sections also have their own variables that handle section properties. These are indicated like so: {$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.

index

index is used to display the current loop index, starting with zero (or the start attribute if given), and incrementing by one (or by the step attribute if given.)

Technical Note: If the step and start section properties are not modified, then this works the same as the iteration section property.

Example 3-50. section property index

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


	OUTPUT:

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

index_prev

index_prev is used to display the previous loop index. on the first loop, this is set to -1.

Example 3-51. section property index_prev

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


	OUTPUT:

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

index_next

index_next is used to display the next loop index. On the last loop, this is still one more than the current index (respecting the setting of the step attribute, if given.)

Example 3-52. section property index_next

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


	OUTPUT:

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

iteration

iteration is used to display the current loop iteration.

NOTE: This is not affected by the section properties start, step and max, unlike the index property.

This was added to Smarty 1.4.4.

Example 3-53. section property iteration

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


	OUTPUT:

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

first

first is set to true if the current section iteration is the first one.

Example 3-54. section property first

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

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

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


	OUTPUT:

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

last

last is set to true if the current section iteration is the last one.

Example 3-55. section property last

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

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

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


	OUTPUT:

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

rownum

rownum is used to display the current loop iteration, starting with one.

Example 3-56. section property rownum

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


	OUTPUT:

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

loop

loop is used to display the last index number that this section looped. This can be used inside or after the section.

Example 3-57. section property index

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

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

	OUTPUT:

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

	There were 3 customers shown above.

show

show is used as a parameter to section. show is a boolean value, true or false. If false, the section will not be displayed. If there is a sectionelse present, that will be alternately displayed.

Example 3-58. section attribute show

	{* $show_customer_info may have been passed from the PHP
	application, to regulate whether or not this section shows *}
	{section name=customer loop=$custid show=$show_customer_info}
	{$smarty.section.customer.rownum} id: {$custid[customer]}<br>
	{/section}

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


	OUTPUT:

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

	the section was shown.

total

total is used to display the number of iterations that this section will loop. This can be used inside or after the section.

This was added to Smarty 1.4.4.

Example 3-59. section property total

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

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

	OUTPUT:

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

	There were 3 customers shown above.

foreach,foreachelse

Attribute NameTypeRequiredDefaultDescription
fromstringYesn/aThe name of the array you are looping through
itemstringYesn/aThe name of the variable that is the current element
keystringNon/aThe name of the variable that is the current key
namestringNon/aThe name of the foreach loop for accessing foreach properties

foreach loops are an alternative to section loops. foreach is used to loop over a single associative array. The syntax for foreach is much easier than section, but as a tradeoff it can only be used for a single array. foreach tags must be paired with /foreach tags. Required parameters are from and item. The name of the foreach loop can be anything you like, made up of letters, numbers and underscores. foreach loops can be nested, and the nested foreach names must be unique from each other. The from variable (usually an array of values) determines the number of times foreach will loop. foreachelse is executed when there are no values in the from variable.

Example 3-60. foreach


{* this example will print out all the values of the $custid array *}
{foreach from=$custid item=curr_id}
	id: {$curr_id}<br>
{/foreach}

OUTPUT:

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

Example 3-61. foreach key

{* The key contains the key for each looped value

assignment looks like this:

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

*}

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

OUTPUT:

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

strip

Many times web designers run into the issue where white space and carriage returns affect the output of the rendered HTML (browser "features"), so you must run all your tags together in the template to get the desired results. This usually ends up in unreadable or unmanagable templates.

Anything within {strip}{/strip} tags in Smarty are stripped of the extra spaces or carriage returns at the beginnings and ends of the lines before they are displayed. This way you can keep your templates readable, and not worry about extra white space causing problems.

Example 3-62. strip tags

{* 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:

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

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.