Table of contents

the smarty is a template engine of php. there are some features of smarty listed blow:

  • split any UI control in smarty, php only provides the data source
  • if ‹ and > can’t parsed as well, we can use $left_delimiter and $right_delimiter instend.
  • function name is case-insensitive but variable is case-sensitive

Smarty Note

Using array veriable in smarty

$user = array("firstname" => "Kent", "lastname" => "Chiu", "email" => "");
$tpl->assign("user", $user);


Using object veriable in smarty

$obj = new UserObject();
$tpl->assign("obj", $obj);


Function in Smarty



  • static values don’t have to be enclosed in quotes
  • it is recommended for literal strings
  • variables should not be in quotes.
  • boolean value can be specified as true, on, and yes, or false, off, and no
{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}


Smarty has several different types of variables. The type of the variable depends on what symbol it is prefixed with (or enclosed within).

variables assigned from php

  • using the sign’$’
  • Associative arrays by ‘.’ (period) symbol
  • Array indexes by ‘[]’ symbol
  • Objects by ‘→’

Associative arrays by ‘.’ (period) symbol

    $smarty = new Smarty;
     array('fax' => '555-222-9876',
     'email' => '',
     'phone' => array('home' => '555-444-3333',
     'cell' => '555-111-1234')));

    {* you can print arrays of arrays as well *}

Array indexes by ‘[]’ symbol

    $smarty = new Smarty;
                     array('555-222-9876',  '',  
                           array('555-444-3333', '555-111-1234')));

    {* you can print arrays of arrays as well *}


Objects by ‘->’

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

variables loaded from config files

there are two syntaxes for accessing variables assigned from config files.

  1. enclosed with double ‘#‘(sharp mark) , ex: #config#
  2. with smarty variable , ex $smarty.config
    pageTitle = "This is mine"
    bodyBgColor = "#eeeeee"
    tableBorderSize = "3"
    tableBgColor = "#bbbbbb"
    rowBgColor = "#cccccc"

enclose by #

    config_load file="foo.conf"}
    <body bgcolor="{#bodyBgColor#}">
    <table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">
    <tr bgcolor="{#rowBgColor#}">

with smarty variable

    {config_load file="foo.conf"}
    <body bgcolor="{$smarty.config.bodyBgColor}">
    <table border="{$smarty.config.tableBorderSize}" bgcolor="{$smarty.config.tableBgColor}">
    <tr bgcolor="{$smarty.config.rowBgColor}">

{$smarty} reserved variable

  1. Request variables(get,post,server,session, … etc)
  2. {$}
  3. {$smarty.const}
  4. {$smarty.capture}
  5. {$smarty.config}
  6. {$smarty.section}, {$smarty.foreach}
  7. {$smarty.template}

Request variables

    {* display value of page from URL (GET) *}
    {* display the variable "page" from a form (POST) *}
    {* display the value of the cookie "username" *}
    {* display the server variable "SERVER_NAME" *}
    {* display the system environment variable "PATH" *}
    {* display the php session variable "id" *}
    {* display the variable "username" from merged get/post/cookies/server/env *}


    {* use the date_format modifier to show current date and time *}
    {$|date_format:"%Y-%m-%d %H:%M:%S"}




The output captured via {capture}..{/capture} construct can be accessed using {$smarty} variable reference to the capture function for more detail.


    {$smarty} variable can be used to refer to loaded config variables. 

reference to the config_load for more detail.

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

{$smarty} variable can be used to refer to ‘section’ and ‘foreach’ loop properties. See docs for section and foreach.


current template name

    {* output myTemplate.tpl *}

Variable Modifiers

  • applied to
    1. variables
    2. custom functions
    3. strings
    4. all php-functions (has two little pitfalls)
  • applied a modifier by (pipe)
  • additional parameters by :(colon)
  • apply to array have to using ‘@’ or it will apply to all elements of array.
    {* apply modifier to a variable *}
    {* modifier with parameters *}
    {* apply modifier to a function parameter *}
    {html_table loop=$myvar|upper}
    {* with parameters *}
    {html_table loop=$myvar|truncate:40:'...'}
    {* apply modifier to literal string *}
    {* using date_format to format the current date *}
    {* apply modifier to a custom function *}
    {mailto|upper address=''}
    {* using  php's str_repeat *}
    {* php's count *}
    {* php's shuffle on servers's ip *}
    (* this will uppercase and truncate the whole array *}
    <select name="name_id">
    {html_options output=$myArray|upper|truncate:20}


    $config['date'] = '%I:%M %p';
    $config['time'] = '%H:%M:%S';
    $smarty->assign('config', $config);
    $smarty->assign('yesterday', strtotime('-1 day'));

    {$|date_format:"%A, %B %e, %Y"}
    {$yesterday|date_format:"%A, %B %e, %Y"}
    <code |h output>
    Jan 1, 2022
    02:33 pm
    Dec 31, 2021
    Monday, December 1, 2021

the formatting control char

  • %a - abbreviated weekday name according to the current locale
  • %A - full weekday name according to the current locale
  • %b - abbreviated month name according to the current locale
  • %B - full month name according to the current locale
  • %c - preferred date and time representation for the current locale
  • %C - century number (the year divided by 100 and truncated to an integer, range 00 to 99)
  • %d - day of the month as a decimal number (range 01 to 31)
  • %D - same as %m/%d/%y
  • %e - day of the month as a decimal number, a single digit is preceded by a space (range 1 to 31)
  • %g - Week-based year within century [00,99]
  • %G - Week-based year, including the century [0000,9999]
  • %h - same as %b
  • %H - hour as a decimal number using a 24-hour clock (range 00 to 23)
  • %I - hour as a decimal number using a 12-hour clock (range 01 to 12)
  • %j - day of the year as a decimal number (range 001 to 366)
  • %k - Hour (24-hour clock) single digits are preceded by a blank. (range 0 to 23)
  • %l - hour as a decimal number using a 12-hour clock, single digits preceeded by a space (range 1 to 12)
  • %m - month as a decimal number (range 01 to 12)
  • %M - minute as a decimal number
  • %n - newline character
  • %p - either `am’ or `pm’ according to the given time value, or the corresponding strings for the current locale
  • %r - time in a.m. and p.m. notation
  • %R - time in 24 hour notation
  • %S - second as a decimal number
  • %t - tab character
  • %T - current time, equal to %H:%M:%S
  • %u - weekday as a decimal number [1,7], with 1 representing Monday
  • %U - week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week
  • %V - The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week.
  • %w - day of the week as a decimal, Sunday being 0
  • %W - week number of the current year as a decimal number, starting with the first Monday as the first day of the first week
  • %x - preferred date representation for the current locale without the time
  • %X - preferred time representation for the current locale without the date
  • %y - year as a decimal number without a century (range 00 to 99)
  • %Y - year as a decimal number including the century
  • %Z - time zone or name or abbreviation
  • %% - a literal `%’ character

Built-in Functions

  • {capture}
  • {config_load}
  • {foreach},{foreachelse}
  • {if},{elseif},{else}
  • {include}
  • {include_php}
  • {insert}
  • {ldelim},{rdelim}
  • {literal}
  • {php}
  • {section},{sectionelse}
  • {strip}


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

    {capture name=some_content assign=popText}
    The server is {$smarty.server.SERVER_NAME|upper} at {$smarty.server.SERVER_ADDR}<br>
    Your ip is {$smarty.server.REMOTE_ADDR}.
    <a href="#" {popup caption='Server Info' text=$popText}>help</a>


    #this is config file comment
    # global variables
    pageTitle = "Main Menu"
    bodyBgColor = #000000
    tableBgColor = #000000
    rowBgColor = #00ff00
    #customer variables section
    pageTitle = "Customer Info"

    {config_load file="example.conf"}
    <title>{#pageTitle#|default:"No title"}</title>
    <body bgcolor="{#bodyBgColor#}">
    <table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">
       <tr bgcolor="{#rowBgColor#}">

    {config_load file='example.conf' section='Customer'}
    <body bgcolor="{#bodyBgColor#}">
    <table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">
       <tr bgcolor="{#rowBgColor#}">


{foreach} properties are

  1. index
  2. iteration
  3. first
  4. last
  5. show
  6. total

Demonstrates the item attributes

    $arr = array(1000, 1001, 1002);
    $smarty->assign('myArray', $arr);

    {foreach from=$myArray item=foo}


Demonstrates the item and key attributes

    $arr = array(9 => 'Tennis', 3 => 'Swimming', 8 => 'Coding');
    $smarty->assign('myArray', $arr);

    {foreach from=$myArray key=k item=v}
       <li>{$k}: {$v}</li>

        <li>9: Tennis</li>
        <li>3: Swimming</li>
        <li>8: Coding</li>

Database example with {foreachelse}

      $search_condition = "where name like '$foo%' ";
      $sql = 'select contact_id, name, nick from contacts '.$search_condition.' order by name';
      $smarty->assign('results', $db->getAssoc($sql) );

    {foreach key=cid item=con from=$results}
        <a href="contact.php?contact_id={$cid}">{$} - {$con.nick}</a><br />
        No items were found in the search


Qualifier Alternates Syntax Example Meaning PHP Equivalent —————— ———— ———————— —————————— ———————- == eq $a eq $b equals == != ne, neq $a neq $b not equals != > gt $a gt $b greater than > < lt $a lt $b less than < >= gte, ge $a ge $b greater than or equal >= ⇐ lte, le $a le $b less than or equal ⇐ === $a === 0 check for identity === ! not not $a negation (unary) ! % mod $a mod $b modulous % is [not] div by $a is not div by 4 divisible by $a % $b == 0 is [not] even $a is not even [not] an even number (unary) $a % 2 == 0 is [not] even by $a is not even by $b grouping level [not] even ($a / $b) % 2 == 0 is [not] odd $a is not odd [not] an odd number (unary) $a % 2 != 0 is [not] odd by $a is not odd by $b [not] an odd grouping ($a / $b) % 2 != 0

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


    {include file="header.tpl" title="Main Menu" table_bgcolor="#c0c0c0" links=$link_array}
    {* body of template goes here *}
    {include file="footer.tpl" logo=""}


{include_php} is pretty much deprecated from Smarty, you can accomplish the same functionality via a custom template function.


{insert} tags work much like {include} tags, except that {insert} tags are NOT cached when template caching is enabled. They will be executed on every invocation of the template.

this function is usful for some content we don’t want to cache, like AD banner or something else.


Used to output ‘{‘ and ‘}’


any context with in the {literal}{/literal} will not interpreted.

    <script language=javascript>
    function isblank(field) {
      if (field.value == '') { 
        return false; 
      } else {
        return true;
    // -->


The {php} tags allow PHP code 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 and not recommended.

{* this template includes a {php} block that assign's the variable $varX *}
   global $foo, $bar;
   if($foo == $bar){
     echo 'This will be sent to browser';
  // assign a variable to Smarty
{* output the variable *}
<strong>{$varX}</strong> is my fav ice cream :-)


A {section} is for looping over arrays of data, unlike {foreach} which is used to loop over a single associative array. Every {section} tag must be paired with a closing {/section} tag.

{section} properties are

  1. index
  2. index_prev
  3. index_next
  4. iteration
  5. first
  6. last
  7. rownum
  8. loop
  9. show
  10. total.

Nested {section}

    $id = array(1001,1002,1003);
    $fullnames = array('John Smith','Jack Jones','Jane Munson');
    $addr = array('253 N 45th', '417 Mulberry ln', '5605 apple st');
    $types = array(
               array( 'home phone', 'cell phone', 'e-mail'),
               array( 'home phone', 'web'),
               array( 'cell phone')
    $smarty->assign('contact_type', $types);
    $info = array(
               array('555-555-5555', '666-555-5555', ''),
               array( '123-456-4', ''),
               array( '0457878')
    $smarty->assign('contact_info', $info);

    {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 />

      id: 1000<br />
      name: John Smith<br />
      address: 253 N 45th<br />
        home phone: 555-555-5555<br />
        cell phone: 666-555-5555<br />
        e-mail:<br />
      id: 1001<br />
      name: Jack Jones<br />
      address: 417 Mulberry ln<br />
        home phone: 123-456-4<br />
        web:<br />
      id: 1002<br />
      name: Jane Munson<br />
      address: 5605 apple st<br />
        cell phone: 0457878<br />

Database sample with {sectionelse}

    $sql = 'select id, name, home, cell, email from contacts '
          ."where name like '$foo%' ";
    $smarty->assign('contacts', $db->getAll($sql));

    {section name=co loop=$contacts}
        <td><a href="view.php?id={$contacts[co].id}">view<a></td>
      <tr><td colspan="5">No items found</td></tr>

.index, .index_prev, .index_next

    $data = array(1001,1002,1003,1004,1005);

    {* $rows[row.index] and $rows[row] are identical in meaning *}
    {section name=row loop=$rows}

    index  id    index_prev prev_id index_next next_id
    0      1001  -1                 1          1002
    1      1002  0          1001    2          1003
    2      1003  1          1002    3          1004
    3      1004  2          1003    4          1005
    4      1005  3          1004    5


show is used as a parameter to section and is a boolean value. If FALSE, the section will not be displayed. If there is a {sectionelse} present, that will be alternately displayed.

    {section name=customer loop=$customers show=$show_customer_info}
      {$smarty.section.customer.rownum} id: {$customers[customer]}<br />
    {if $}
      the section was shown.
      the section was not shown.

    1 id: 1000<br />
    2 id: 1001<br />
    3 id: 1002<br />
    the section was shown.


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 unmanageable templates. Anything within {strip}{/strip} tags 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.

{* the following will be all run into one line upon output *}
<table border='0'>
   <a href="{$url}">
    <font color="red">This is a test</font>

    <table border='0'><tr><td><a href="http://. snipped...</a></td></tr></table>

if any white space or ‘CR’ charachter affect web layout, we could use {srip} to avoid it

Custom Functions

Smarty comes with several custom functions that you can use in the templates.

  • {assign}
  • {counter}
  • {cycle}
  • {debug}
  • {eval}
  • {fetch}
  • {html_checkboxes}
  • {html_image}
  • {html_options}
  • {html_radios}
  • {html_select_date}
  • {html_select_time}
  • {html_table}
  • {mailto}
  • {math}
  • {popup}
  • {popup_init}
  • {textformat}


    {assign var='name' value='Bob'}
    The value of $name is {$name}.

    The value of $name is Bob.

examples 2:

    {assign var=running_total value=`$running_total+$some_array[row].some_value`}


{counter} will remember the count on each iteration.

    {* initialize the count *}
    {counter start=0 skip=2}<br />
    {counter}<br />
    {counter}<br />
    {counter}<br />

    0<br />
    2<br />
    4<br />
    6<br />


{cycle} is used to alternate a set of values. This makes it easy to for example, alternate between two or more colors in a table, or cycle through an array of values.

  • the advance attribute is used to repeat a value. When set to FALSE, the next call to {cycle} will print the same value.
    {section name=rows loop=$data}
    <tr bgcolor="{cycle values="#eeeeee,#d0d0d0"}">

    <tr bgcolor="#eeeeee">
    <tr bgcolor="#d0d0d0">
    <tr bgcolor="#eeeeee">


{debug} dumps the debug console to the page. This works regardless of the debug settings in the php script.


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

    {config_load file='setup.conf'}
    {eval var=$foo}
    {eval var=#title#}
    {eval var=#ErrorCity#}
    {eval var=#ErrorState# assign='state_error'}

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


{fetch} is used to retrieve files from the local file system, http, or ftp and display the contents.

    {* include some javascript in your template *}
    {fetch file='/export/httpd/'}
    {* embed some weather text in your template from another web site *}
    {fetch file=''}
    {* fetch a news headline file via ftp *}
    {fetch file=''}
    {* as above but with variables *}
    {fetch file="ftp://`$user`:`$password`@`$server`/`$path`"}
    {* assign the fetched contents to a template variable *}
    {fetch file='' assign='weather'}
    {if $weather ne ''}
      <div id="weather">{$weather}</div>


    $smarty->assign('cust_ids', array(1000,1001,1002,1003));
    $smarty->assign('cust_names', array(
                                    'Joe Schmoe',
                                    'Jack Smith',
                                    'Jane Johnson',
                                    'Charlie Brown')
    $smarty->assign('customer_id', 1001);

    {html_checkboxes name='id' values=$cust_ids output=$cust_names 
       selected=$customer_id  separator='<br />'}

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


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

    <img src="pumpkin.jpg" alt="" width="44" height="68" />
    <img src="/path/from/docroot/pumpkin.jpg" alt="" width="44" height="68" />
    <img src="../path/relative/to/currdir/pumpkin.jpg" alt="" width="44" height="68" />

Technical Note: {html_image} requires a hit to the disk to read the image and calculate the height and width. If you don’t use template caching, it is generally better to avoid {html_image} and leave image tags static for optimal performance.


    $smarty->assign('myOptions', array(
                                    1800 => 'Joe Schmoe',
                                    9904 => 'Jack Smith',
                                    2003 => 'Charlie Brown')
    $smarty->assign('mySelect', 9904);

    {html_options name=foo options=$myOptions selected=$mySelect}

    <select name="foo">
    <option label="Joe Schmoe" value="1800">Joe Schmoe</option>
    <option label="Jack Smith" value="9904" selected="selected">Jack Smith</option>
    <option label="Charlie Brown" value="2003">Charlie Brown</option>


    $smarty->assign('cust_ids', array(1000,1001,1002,1003));
    $smarty->assign('cust_names', array(
                                  'Joe Schmoe',
                                  'Jack Smith',
                                  'Jane Johnson',
                                  'Charlie Brown')
    $smarty->assign('customer_id', 1001);

    {html_radios name='id' values=$cust_ids output=$cust_names
           selected=$customer_id separator='<br />'}

    <label for="id_1000">
    <input type="radio" name="id" value="1000" id="id_1000" />Joe Schmoe</label><br />
    <label for="id_1001"><input type="radio" name="id" value="1001" id="id_1001" checked="checked" />Jack Smith</label><br />
    <label for="id_1002"><input type="radio" name="id" value="1002" id="id_1002" />Jane Johnson</label><br />
    <label for="id_1003"><input type="radio" name="id" value="1003" id="id_1003" />Charlie Brown</label><br />



    <select name="Date_Month">
    <option value="1">January</option>
    <option value="2">February</option>
    <option value="3">March</option>
      ..... snipped .....
    <option value="10">October</option>
    <option value="11">November</option>
    <option value="12" selected="selected">December</option>
    <select name="Date_Day">
    <option value="1">01</option>
    <option value="2">02</option>
    <option value="3">03</option>
      ..... snipped .....
    <option value="11">11</option>
    <option value="12">12</option>
    <option value="13" selected="selected">13</option>
    <option value="14">14</option>
    <option value="15">15</option>
      ..... snipped .....
    <option value="29">29</option>
    <option value="30">30</option>
    <option value="31">31</option>
    <select name="Date_Year">
    <option value="2006" selected="selected">2006</option>


    {html_select_time use_24_hours=true}

    <select name="Time_Hour">
    <option value="00">00</option>
    <option value="01">01</option>
    ... snipped ....
    <option value="08">08</option>
    <option value="09" selected>09</option>
    <option value="10">10</option>
    ... snipped ....
    <option value="22">22</option>
    <option value="23">23</option>
    <select name="Time_Minute">
    <option value="00">00</option>
    <option value="01">01</option>
    ... snipped ....
    <option value="19">19</option>
    <option value="20" selected>20</option>
    <option value="21">21</option>
    ... snipped ....
    <option value="58">58</option>
    <option value="59">59</option>
    <select name="Time_Second">
    <option value="00">00</option>
    <option value="01">01</option>
    ... snipped ....
    <option value="22">22</option>
    <option value="23" selected>23</option>
    <option value="24">24</option>
    ... snipped ....
    <option value="58">58</option>
    <option value="59">59</option>
    <select name="Time_Meridian">
    <option value="am" selected>AM</option>
    <option value="pm">PM</option>


    $smarty->assign( 'data', array(1,2,3,4,5,6,7,8,9) );
    $smarty->assign( 'tr', array('bgcolor="#eeeeee"','bgcolor="#dddddd"') );

    {**** Example One ****}
    {html_table loop=$data}
    {**** Example Two ****}
    {html_table loop=$data cols=4 table_attr='border="0"'}
    {**** Example Three ****}
    {html_table loop=$data cols="first,second,third,fourth" tr_attr=$tr}

    <!-- example One output -->
    <table border="1">
    <!-- example Two output -->
    <table border="0">
    <!-- example Three output -->
    <table border="1">
    <tr bgcolor="#eeeeee"><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr bgcolor="#dddddd"><td>5</td><td>6</td><td>7</td><td>8</td></tr>
    <tr bgcolor="#eeeeee"><td>9</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>


    {mailto address=""}
    <a href="" ></a>
    {mailto address="" text="send me some mail"}
    <a href="" >send me some mail</a>
    {mailto address="" encode="javascript"}
    <script type="text/javascript" language="javascript">
       eval(unescape('%64%6f% ... snipped ...%61%3e%27%29%3b'))
    {mailto address="" encode="hex"}
    <a href="mailto:%6d%65.. snipped..3%6f%6d">&#x6d;&..snipped...#x6f;&#x6d;</a>
    {mailto address="" subject="Hello to you!"}
    <a href="" ></a>
    {mailto address="" cc=","}
    <a href="" ></a>
    {mailto address="" extra='class="email"'}
    <a href="" class="email"></a>
    {mailto address="" encode="javascript_charcode"}
    <script type="text/javascript" language="javascript">
        {document.write(String.fromCharCode(60,97, ... snipped ....60,47,97,62))}


    {* ====== example a =====   *}
    {* $height=4, $width=5 *}
    {math equation="x + y" x=$height y=$width}
    {* output is 9 *}
    {* ====== example b =====   *}
    {* $row_height = 10, $row_width = 20, #col_div# = 2, assigned in template *}
    {math equation="height * width / division"
    {* output is 100 *}
    {* ====== example c =====   *}
    {* you can use parenthesis *}
    {math equation="(( x + y ) / z )" x=2 y=10 z=2}
    {* output is 6 *}
    {* ====== example d =====   *}
    {* you can supply a format parameter in sprintf format *}
    {math equation="x + y" x=4.4444 y=5.0000 format="%.2f"}
    {* output is 9.44 *}

    {* popup_init must be called once at the top of the page *}
    {popup_init src='/javascripts/overlib.js'}
    {* create a link with a popup window when you move your mouse over *}
    <a href="mypage.html" {popup text='This link takes you to my page!'}>mypage</a>
    {* you can use html, links, etc in your popup text *}
    <a href="mypage.html" {popup sticky=true caption='mypage contents'
    snapx=10 snapy=10 trigger='onClick'}>mypage</a>
    {* a popup  over a table cell *}
    <tr><td {popup caption='Part details' text=$part_long_description}>{$part_number}</td></tr>

{popup} is an integration of overLib, a library used for popup windows. These are used for context sensitive information, such as help windows or tooltips.

    {* popup_init must be called once at the top of the page *}
    {popup_init src='javascripts/overlib/overlib.js'}
    {* fully qualified url example *}
    {popup_init src=''}
    // the first example will output
    <div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
    <script type="text/javascript" language="JavaScript" src="javascripts/overlib/overlib.js"></script>


    {textformat wrap=40 indent=4}
       This is foo.
       This is foo.
       This is foo.
       This is foo.
       This is foo.
       This is foo.
       This is bar.
       bar foo bar foo     foo.
       bar foo bar foo     foo.
       bar foo bar foo     foo.
       bar foo bar foo     foo.
       bar foo bar foo     foo.
       bar foo bar foo     foo.
       bar foo bar foo     foo.

    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.

debug in smarty

Expect to use {debug}, an other way is enabled smarty debugger will pop a windows and display all useful information within it (a.k.a debuging console).

    $smarty->debugging = true;
    $smarty->debug_tpl = SMARTY_DIR . "debug.tpl";

you can also combine the PHP_Debug with smarty debugger page, check here to get more details.


  • SMARTY_DIR - full system path
  • SMARTY_CORE_DIR - full system path to the location of the Smarty core files

Smarty Class Variables

  • $template_dir
  • $compile_dir
  • $config_dir
  • $plugins_dir
  • $debugging
  • $debug_tpl
  • $debugging_ctrl
  • $autoload_filters
  • $compile_check
  • $force_compile
  • $caching
  • $cache_dir
  • $cache_lifetime
  • $cache_handler_func
  • $cache_modified_check
  • $config_overwrite
  • $config_booleanize
  • $config_read_hidden
  • $config_fix_newlines
  • $default_template_handler_func
  • $php_handling
  • $security
  • $secure_dir
  • $security_settings
  • $trusted_dir-
  • $left_delimiter
  • $right_delimiter
  • $compiler_class
  • $request_vars_order
  • $request_use_auto_globals
  • $error_reporting
  • $compile_id
  • $use_sub_dirs
  • $default_modifiers
  • $default_resource_type

Smarty Class Methods

  • append() – append an element to an assigned array
  • append_by_ref() – append values by reference
  • assign() – assign values to the templates
  • assign_by_ref() – assign values by reference
  • clear_all_assign() – clears the values of all assigned variables
  • clear_all_cache() – clears the entire template cache
  • clear_assign() – clears the value of an assigned variable
  • clear_cache() – clears the cache for a specific template
  • clear_compiled_tpl() – clears the compiled version of the specified template resource
  • clear_config() – clears assigned config variables
  • config_load() – loads config file data and assigns it to the template
  • display() – displays the template
  • fetch() – returns the template output
  • get_config_vars() – returns the given loaded config variable value
  • get_registered_object() – returns a reference to a registered object
  • get_template_vars() – returns assigned variable value(s)
  • is_cached() – returns true if there is a valid cache for this template
  • load_filter() – load a filter plugin
  • register_block() – dynamically register block functions plugins
  • register_compiler_function() – dynamically register a compiler function plugin
  • register_function() – dynamically register template function plugins
  • register_modifier() – dynamically register modifier plugin
  • register_object() – register an object for use in the templates
  • register_outputfilter() – dynamically register outputfilters
  • register_postfilter() – dynamically register postfilters
  • register_prefilter() – dynamically register prefilters
  • register_resource() – dynamically register resources
  • trigger_error() – output an error message
  • template_exists() – checks whether the specified template exists
  • unregister_block() – dynamically unregister block function plugins
  • unregister_compiler_function() – dynamically unregister a compiler function
  • unregister_function – dynamically unregister template function plugin
  • unregister_modifier() – dynamically unregister modifier plugin
  • unregister_object() – dynamically unregister an object
  • unregister_outputfilter() – dynamically unregister an output filter
  • unregister_postfilter() – dynamically unregister a postfilter
  • unregister_prefilter() – dynamically unregister a prefilter
  • unregister_resource() – dynamically unregister a resource plugin


    $smarty = new Smarty;
    $smarty->caching = 1;


The is_cached() function can be used to test if a template has a valid cache or not. If you have a cached template that requires something like a database fetch, you can use this to skip that process.

WYou 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 side of the page. By using the {insert} function for the banner, you can keep this element dynamic within the cached content.

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

push objects to page

  1. register objects to the template. (RECOMMANDED)
  2. assign() or assign_by_ref() function.
    // the object
    class My_Object {
        function meth1($params, &$smarty_obj) {
            return 'this is my meth1';
    $myobj = new My_Object;
    // registering the object (will be by reference)
    // if we want to restrict access to certain methods or properties, list them
    // if you want to use the traditional object parameter format, pass a boolean of false
    // We can also assign objects. assign_by_ref when possible.
    $smarty->assign_by_ref('myobj', $myobj);

    {* access our registered object *}
    {foobar->meth1 p1='foo' p2=$bar}
    {* you can also assign the output *}
    {foobar->meth1 p1='foo' p2=$bar assign='output'}
    the output was {$output}
    {* access our assigned object *}


  1. prefilters - activated before templates complied
  2. postfilters - activated after templates complied
  3. output filters - invoked by display() or fetch()


Can be used for filter out some information that should not output to browser, ex: comment

    // put this in your application
    function remove_dw_comments($tpl_source, &$smarty)
        return preg_replace("/<!--#.*-->/U",'',$tpl_source);
    // register the prefilter


it is useful if want to add some content to all templates.

    // put this in your application
    function add_header_comment($tpl_source, &$smarty)
        return "<?php echo \"<!-- Created by Smarty! -->\n\"; ?>\n".$tpl_source;
    // register the postfilter

the postfilter above will make the compiled Smarty template index.tpl look like:

    <!-- Created by Smarty! -->
    {* rest of template content... *}

output filters