PHP - Smarty - done reading - done reading - plugins - plugins - plugins - custom function

How can we get started?

mkdir libraries
cd libraries

unzip ...

cd .. // back to the main application folder

// Smarty requires four directories which are by default named templates/, templates_c/, configs/ and cache/
// Each of these are definable by the Smarty class properties $template_dir, 
// $compile_dir, $config_dir, and $cache_dir respectively
// You can verify if your system has the correct access rights for these directories with testInstall().
// Smarty will need write access (windows users please ignore) to the $compile_dir and $cache_dir directories 
// (templates_c/ and cache/), so be sure the web server user account can write to them. 
// This is usually user “nobody” and group “nobody”. For OS X users, the default is user “www” and group “www”. 
// If you are using Apache, you can look in your httpd.conf file to see what user and group are being used.

mkdir smarty
cd smarty
mkdir templates templates_c cache config
chown nobody:nobody /web/
chmod 770 /web/
chown nobody:nobody /web/
chmod 770 /web/

$rootDir = __DIR__;
require_once($rootDir . '/vendor/swiftmailer/swiftmailer/lib/swift_required.php');
require_once($rootDir . '/libraries/smarty-3.1.27/libs/Smarty.class.php');
ini_set('date.timezone', 'Europe/Berlin');

$smarty = new Smarty();
$smarty->setTemplateDir($rootDir . '/smarty/templates/');
$smarty->setCompileDir($rootDir . '/smarty/templates_c/');
$smarty->setConfigDir($rootDir . '/smarty/configs/');
$smarty->setCacheDir($rootDir . '/smarty/cache/');

//$smarty->debugging = true;


chmod 770 will be fairly tight security, it only allows user “nobody” and group “nobody” read/write access to the directories. If you would like to open up read access to anyone (mostly for your own convenience of viewing these files), you can use 775 instead.

Now create the index.tpl file inside the templates directory:

{* Smarty *}
Whatever you want to put here!

How can we evaluate a template? How can we get the result of a template?


Why should we extend the Smarty class?

We can extend the Smarty class so that instead of repeatedly setting directory paths, assigning the same vars, etc., we can do that in one place.

Lets create a new directory /php/includes/guestbook/ and make a new file called setup.php. In our example environment, /php/includes is in our include_path. Be sure you set this up too, or use absolute file paths.


// load Smarty library

// The setup.php file is a good place to load
// required application library files, and you
// can do that right here. An example:
// require('guestbook/guestbook.lib.php');

class Smarty_GuestBook extends Smarty {

   function __construct()

        // Class Constructor.
        // These automatically get set with each new instance.



        $this->caching = Smarty::CACHING_LIFETIME_CURRENT;
        $this->assign('app_name', 'Guest Book');


Now lets alter the index.php file to use setup.php:

$smarty = new Smarty_GuestBook();

Now you see it is quite simple to bring up an instance of Smarty, just use Smarty_GuestBook() which automatically initializes everything for our application.

How can we comment out a block of smarty?

{* Smarty *}

{* Smarty *} is a template comment. It is not required, but it is good practice to start all your template files with this comment. It makes the file easy to recognize regardless of the file extension. For example, text editors could recognize the file and turn on special syntax highlighting.


{$foo}        <-- displaying a simple variable (non array/object)
{$foo[4]}     <-- display the 5th element of a zero-indexed array
{$}    <-- display the "bar" key value of an array, similar to PHP $foo['bar']
{$foo.$bar}   <-- display variable key value of an array, similar to PHP $foo[$bar]
{$foo->bar}   <-- display the object property "bar"
{$foo->bar()} <-- display the return value of object method "bar"
{#foo#}       <-- display the config file variable "foo"
{$} <-- synonym for {#foo#}
{$foo[bar]}   <-- syntax only valid in a section loop, see {section}
{assign var=foo value='baa'}{$foo} <--  displays "baa", see {assign}

Many other combinations are allowed

{$foo->bar($baz,2,$bar)} <-- passing parameters
{"foo"}       <-- static values are allowed

{* display the server variable "SERVER_NAME" ($_SERVER['SERVER_NAME'])*}

Math and embedding tags:

{$x+$y}                             // will output the sum of x and y.
{assign var=foo value=$x+$y}        // in attributes 
{$foo[$x+3]}                        // as array index
{$foo={counter}+3}                  // tags within tags
{$foo="this is message {counter}"}  // tags within double quoted strings

Defining Arrays:

{assign var=foo value=[1,2,3]}
{assign var=foo value=['y'=>'yellow','b'=>'blue']}
{assign var=foo value=[1,[9,8],3]}   // can be nested

Short variable assignment:

{$foo = strlen($bar)}               // function in assignment
{$foo = myfunct( ($x+$y)*3 )}       // as function parameter 
{$}                        // assign to specific array element
{$foo[]=1}                          // appending to an array

Smarty "dot" syntax (note: embedded {} are used to address ambiguities):

{$foo.a.b.c}        =>  $foo['a']['b']['c'] 
{$foo.a.$b.c}       =>  $foo['a'][$b]['c']         // with variable index
{$foo.a.{$b+4}.c}   =>  $foo['a'][$b+4]['c']       // with expression as index
{$foo.a.{$b.c}}     =>  $foo['a'][$b['c']]         // with nested index

PHP-like syntax, alternative to "dot" syntax:

{$foo[1]}             // normal access
{$foo[$x+$x]}         // index may contain any expression
{$foo[$bar[1]]}       // nested index
{$foo[section_name]}  // smarty {section} access, not array access!

Variable variables:

$foo                     // normal variable
$foo_{$bar}              // variable name containing other variable 
$foo_{$x+$y}             // variable name containing expressions 
$foo_{$bar}_buh_{$blar}  // variable name with multiple segments
{$foo_{$x}}              // will output the variable $foo_1 if $x has a value of 1.

Object chaining:


Direct PHP function access:


{config_load file="colors.conf"}

{include file="header.tpl"}
{insert file="banner_ads.tpl" title="My Site"}

{if $logged_in}
    Welcome, <span style="color:{#fontColor#}">{$name}!</span>
    hi, {$name}

{include file="footer.tpl"}

{assign var=foo value=$buh+$bar|strlen}  // more complex expression
{html_select_date display_days=true}
{mailto address=""}
<select name="company_id">
  {html_options options=$companies selected=$company_id}

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

What is the purpose of the {literal}…{/literal} construct?

It is sometimes desirable or even necessary to have Smarty ignore sections it would otherwise parse. A classic example is embedding Javascript or CSS code in a template. The problem arises as those languages use the { and } characters which are also the default delimiters for Smarty.

A good practice for avoiding escapement altogether is by separating your Javascript/CSS into their own files and use standard HTML methods to access them. This will also take advantage of browser script caching. When you need to embed Smarty variables/functions into your Javascript/CSS, then the following applies.

In Smarty templates, the { and } braces will be ignored so long as they are surrounded by white space. This behavior can be disabled by setting the Smarty class variable $auto_literal to false.

   // the following braces are ignored by Smarty
   // since they are surrounded by whitespace
   function foobar {
   // this one will need literal escapement
    function bazzy {alert('foobar!');}

{literal}..{/literal} blocks are used for escaping blocks of template logic. You can also escape the braces individually with {ldelim},{rdelim} tags or {$smarty.ldelim},{$smarty.rdelim} variables.

Smarty's default delimiters { and } cleanly represent presentational content. However if another set of delimiters suit your needs better, you can change them with Smarty's $left_delimiter and $right_delimiter values.

Changing delimiters affects ALL template syntax and escapement. Be sure to clear out cache and compiled files if you decide to change them.

$smarty->left_delimiter = '<!--{';
$smarty->right_delimiter = '}-->';

$smarty->assign('foo', 'bar');
$smarty->assign('name', 'Albert');

What is a custom function?

Custom functions are additional functions implemented via plugins. They can be modified to your liking, or you can create new ones. {html_options} is an example of a custom function.

Calling PHP from inside Smarty:


Smarty filter / modifier:

<span title="{strip}{$|strip_tags}{/strip}" style='float:left'>
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License