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

<?php
$user = array("firstname" => "Kent", "lastname" => "Chiu", "email" => "kent.chiu@mail.com");
$tpl->assign("user", $user);
?>

{$user.firstname}
{$user.lastname}
{$user.email}

Using object veriable in smarty

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

{$obj->firstname}
{$obj->lastname}
{$obj->method()}

Function in Smarty

{$var|function}
{$var|function:"argument(option)"}

attributes

  • 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}
</SELECT>

variables

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;
    $smarty->assign('Contacts',
     array('fax' => '555-222-9876',
     'email' => 'zaphod@slartibartfast.com',
     'phone' => array('home' => '555-444-3333',
     'cell' => '555-111-1234')));
    $smarty->display('index.tpl');

    {$Contacts.fax}<br>
    {$Contacts.email}<br>
    {* you can print arrays of arrays as well *}
    {$Contacts.phone.home}<br>
    {$Contacts.phone.cell}<br>

Array indexes by ‘[]’ symbol

    $smarty = new Smarty;
    $smarty->assign('Contacts', 
                     array('555-222-9876',  'zaphod@slartibartfast.com',  
                           array('555-444-3333', '555-111-1234')));
    $smarty->display('index.tpl');

    {$Contacts[0]}<br>
    {$Contacts[1]}<br>
    {* you can print arrays of arrays as well *}
    {$Contacts[2][0]}<br>
    {$Contacts[2][1]}<br>

    555-222-9876<br>
    zaphod@slartibartfast.com<br>
    555-444-3333<br>
    555-111-1234<br>

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"}
    <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>

with smarty variable

    {config_load file="foo.conf"}
    <html>
    <title>{$smarty.config.pageTitle}</title>
    <body bgcolor="{$smarty.config.bodyBgColor}">
    <table border="{$smarty.config.tableBorderSize}" bgcolor="{$smarty.config.tableBgColor}">
    <tr bgcolor="{$smarty.config.rowBgColor}">
        <td>First</td>
        <td>Last</td>
        <td>Address</td>
    </tr>
    </table>
    </body>
    </html>

{$smarty} reserved variable

  1. Request variables(get,post,server,session, … etc)
  2. {$smarty.now}
  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) http://www.domain.com/index.php?page=foo *}
    {$smarty.get.page}
     
    {* display the variable "page" from a form (POST) *}
    {$smarty.post.page}
     
    {* display the value of the cookie "username" *}
    {$smarty.cookies.username}
     
    {* display the server variable "SERVER_NAME" *}
    {$smarty.server.SERVER_NAME}
     
    {* display the system environment variable "PATH" *}
    {$smarty.env.PATH}
     
    {* display the php session variable "id" *}
    {$smarty.session.id}
     
    {* display the variable "username" from merged get/post/cookies/server/env *}
    {$smarty.request.username}

{$smarty.now}

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

{$smarty.const}

    {$smarty.const._MY_CONST_VAL}

{$smarty.capture}

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

{$smarty.config}

    {$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.

{$smarty.template}

current template name

    {$smarty.template};
    {* 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 *}
    {$title|upper}
     
    {* modifier with parameters *}
    {$title|truncate:40:'...'}
     
    {* apply modifier to a function parameter *}
    {html_table loop=$myvar|upper}
     
    {* with parameters *}
    {html_table loop=$myvar|truncate:40:'...'}
     
    {* apply modifier to literal string *}
    {'foobar'|upper}
     
    {* using date_format to format the current date *}
    {$smarty.now|date_format:"%Y/%m/%d"}
     
    {* apply modifier to a custom function *}
    {mailto|upper address='smarty@example.com'}
     
    {* using  php's str_repeat *}
    {'='|str_repeat:80}
     
    {* php's count *}
    {$myArray|@count}
     
    {* php's shuffle on servers's ip *}
    {$smarty.server.SERVER_ADDR|shuffle}
     
    (* this will uppercase and truncate the whole array *}
    <select name="name_id">
    {html_options output=$myArray|upper|truncate:20}
    </select>

date_format

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

    {$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"}
    </ocde>
     
    <code |h output>
    Jan 1, 2022
    01/01/22
    02:33 pm
    Dec 31, 2021
    Monday, December 1, 2021
    14:33:00

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}

{capture}

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

    {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}.
    {/capture}
    <a href="#" {popup caption='Server Info' text=$popText}>help</a>

{config_load}

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

    {config_load file="example.conf"}
     
    <html>
    <title>{#pageTitle#|default:"No title"}</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_load file='example.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>

{foreach},{foreachelse}

{foreach} properties are

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

Demonstrates the item attributes

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

    <ul>
    {foreach from=$myArray item=foo}
        <li>{$foo}</li>
    {/foreach}
    </ul>

    <ul>
        <li>1000</li>
        <li>1001</li>
        <li>1002</li>
    </ul>

Demonstrates the item and key attributes

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

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

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

Database example with {foreachelse}

    <?php
      $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.name} - {$con.nick}</a><br />
    {foreachelse}
        No items were found in the search
    {/foreach}

{if},{elseif},{else}

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.
    {else}
        Welcome, whatever you are.
    {/if}

{include}

    {include file="header.tpl" title="Main Menu" table_bgcolor="#c0c0c0" links=$link_array}
     
    {* body of template goes here *}
     
    {include file="footer.tpl" logo="http://my.domain.com/logo.gif"}

{include_php}

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

{insert}

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

{ldelim},{rdelim}

Used to output ‘{‘ and ‘}’

{literal}

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

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

{php}

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 *}
{php}
   global $foo, $bar;
   if($foo == $bar){
     echo 'This will be sent to browser';
   }
  // assign a variable to Smarty
  $this->assign('varX','Toffee');
{/php}
{* output the variable *}
<strong>{$varX}</strong> is my fav ice cream :-)

{section},{sectionelse}

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}

    <?php
     
    $id = array(1001,1002,1003);
    $smarty->assign('custid',$id);
     
    $fullnames = array('John Smith','Jack Jones','Jane Munson');
    $smarty->assign('name',$fullnames);
     
    $addr = array('253 N 45th', '417 Mulberry ln', '5605 apple st');
    $smarty->assign('address',$addr);
     
    $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', 'john@myexample.com'),
               array( '123-456-4', 'www.example.com'),
               array( '0457878')
            );
    $smarty->assign('contact_info', $info);
     
    ?> 

    {section name=customer loop=$custid}
    <hr>
      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}
    {/section}

    <hr>
      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: john@myexample.com<br />
    <hr>
      id: 1001<br />
      name: Jack Jones<br />
      address: 417 Mulberry ln<br />
        home phone: 123-456-4<br />
        web: www.example.com<br />
    <hr>
      id: 1002<br />
      name: Jane Munson<br />
      address: 5605 apple st<br />
        cell phone: 0457878<br />

Database sample with {sectionelse}

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

    <table>
    <tr><th>&nbsp;</th><th>Name></th><th>Home</th><th>Cell</th><th>Email</th></tr>
    {section name=co loop=$contacts}
      <tr>
        <td><a href="view.php?id={$contacts[co].id}">view<a></td>
        <td>{$contacts[co].name}</td>
        <td>{$contacts[co].home}</td>
        <td>{$contacts[co].cell}</td>
        <td>{$contacts[co].email}</td>
      <tr>
    {sectionelse}
      <tr><td colspan="5">No items found</td></tr>
    {/section}
    </table>

.index, .index_prev, .index_next

    <?php
    $data = array(1001,1002,1003,1004,1005);
    $smarty->assign('rows',$data);
    ?> 

    {* $rows[row.index] and $rows[row] are identical in meaning *}
    <table>
      <tr>
        <th>index</th><th>id</th>
        <th>index_prev</th><th>prev_id</th>
        <th>index_next</th><th>next_id</th>
      </tr>
    {section name=row loop=$rows}
      <tr>
        <td>{$smarty.section.row.index}</td><td>{$rows[row]}</td>
        <td>{$smarty.section.row.index_prev}</td><td>{$rows[row.index_prev]}</td>
        <td>{$smarty.section.row.index_next}</td><td>{$rows[row.index_next]}</td>
      </tr>
    {/section}
    </table>

    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

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 />
    {/section}
     
    {if $smarty.section.customer.show}
      the section was shown.
    {else}
      the section was not shown.
    {/if}

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

{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 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 *}
{strip}
<table border='0'>
 <tr>
  <td>
   <a href="{$url}">
    <font color="red">This is a test</font>
   </a>
  </td>
 </tr>
</table>
{/strip}

    <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}

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

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

{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"}">
       <td>{$data[rows]}</td>
    </tr>
    {/section}

    <tr bgcolor="#eeeeee">
       <td>1</td>
    </tr>
    <tr bgcolor="#d0d0d0">
       <td>2</td>
    </tr>
    <tr bgcolor="#eeeeee">
       <td>3</td>
    </tr>

{debug}

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

{eval}

    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'}
    {$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}

{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/www.example.com/docs/navbar.js'}
     
    {* embed some weather text in your template from another web site *}
    {fetch file='http://www.myweather.com/68502/'}
     
    {* fetch a news headline file via ftp *}
    {fetch file='ftp://user:password@ftp.example.com/path/to/currentheadlines.txt'}
    {* as above but with variables *}
    {fetch file="ftp://`$user`:`$password`@`$server`/`$path`"}
     
    {* assign the fetched contents to a template variable *}
    {fetch file='http://www.myweather.com/68502/' assign='weather'}
    {if $weather ne ''}
      <div id="weather">{$weather}</div>
    {/if}

{html_checkboxes}

    <?php
     
    $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}

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

{html_options}

    <?php
    $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>
    </select>

{html_radios}

    <?php
     
    $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 />

{html_select_date}

    {html_select_date}

    <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>
    <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>
    <select name="Date_Year">
    <option value="2006" selected="selected">2006</option>
    </select>

{html_select_time}

    {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>
    <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>
    <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>
    <select name="Time_Meridian">
    <option value="am" selected>AM</option>
    <option value="pm">PM</option>
    </select>

{html_table}

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

    {**** 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">
    <tbody>
    <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>
    </tbody>
    </table>
     
     
     
    <!-- example Two output -->
    <table border="0">
    <tbody>
    <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>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
    </tbody>
    </table>
     
    <!-- example Three output -->
    <table border="1">
    <thead>
    <tr>
    <th>first</th><th>second</th><th>third</th><th>fourth</th>
    </tr>
    </thead>
    <tbody>
    <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>
    </tbody>
    </table>

{mailto}

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

{math}

    {* ====== 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"
      height=$row_height
      width=$row_width
      division=#col_div#}
     
    {* 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'
    text="<ul><li>links</li><li>pages</li><li>images</li></ul>"
    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.

    <head>
    {* 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='http://myserver.org/my_js_libs/overlib/overlib.js'}
    </head>
     
    // the first example will output
    <head>
    <div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
    <script type="text/javascript" language="JavaScript" src="javascripts/overlib/overlib.js"></script>
    </head>

{textformat}

    {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.
     
    {/textformat}

    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.

Constants

  • 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

Caching

    <?php
    require('Smarty.class.php');
    $smarty = new Smarty;
     
    $smarty->caching = 1;
     
    $smarty->display('index.tpl');
    ?> 

is_cached()

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.

    <?php
    require('Smarty.class.php');
    $smarty = new Smarty;
     
    $smarty->caching = 1;
     
    if(!$smarty->is_cached('index.tpl')) {
        // No cache available, do variable assignments here.
        $contents = get_database_contents();
        $smarty->assign($contents);
    }
     
    $smarty->display('index.tpl');
    ?> 

push objects to page

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

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

Filters

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

prefilters

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

    <?php
    // put this in your application
    function remove_dw_comments($tpl_source, &$smarty)
    {
        return preg_replace("/<!--#.*-->/U",'',$tpl_source);
    }
     
    // register the prefilter
    $smarty->register_prefilter('remove_dw_comments');
    $smarty->display('index.tpl');
    ?> 

postfilters

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

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

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

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

output filters

TBD