PHP - Smarty

http://www.smarty.net/docs/en/ - done reading
http://www.smarty.net/docs/en/installing.smarty.basic.tpl - done reading
http://www.smarty.net/docs/en/language.variables.tpl
http://www.smarty.net/docs/en/plugins.tpl - plugins
http://www.smarty.net/docs/en/language.function.html.options.tpl - plugins
http://www.smarty.net/docs/en/api.register.plugin.tpl - plugins
http://www.smarty.net/docs/en/language.syntax.quotes.tpl - custom function

http://php.net/ref.classobj

How can we get started?

mkdir libraries
cd libraries

wget https://github.com/smarty-php/smarty/archive/master.zip
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/www.example.com/guestbook/templates_c/
chmod 770 /web/www.example.com/guestbook/templates_c/
chown nobody:nobody /web/www.example.com/guestbook/cache/
chmod 770 /web/www.example.com/guestbook/cache/

$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->assign('title','SolarChampions');
$smarty->assign('site_name','SolarChampions.com');
$smarty->assign('short_name','SolarChampions');
//$smarty->debugging = true;

$smarty->display('index.tpl');

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?

$smarty->fetch('filename.tpl');

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.

<?php

// load Smarty library
require('Smarty.class.php');

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

        parent::__construct();

        $this->setTemplateDir('/web/www.example.com/guestbook/templates/');
        $this->setCompileDir('/web/www.example.com/guestbook/templates_c/');
        $this->setConfigDir('/web/www.example.com/guestbook/configs/');
        $this->setCacheDir('/web/www.example.com/guestbook/cache/');

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

}
?>

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

/web/www.example.com/guestbook/htdocs/index.php
<?php
require('guestbook/setup.php');
$smarty = new Smarty_GuestBook();
$smarty->assign('name','Ned');
$smarty->display('index.tpl');
?>

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

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.

Examples:

{$foo}        <-- displaying a simple variable (non array/object)
{$foo[4]}     <-- display the 5th element of a zero-indexed array
{$foo.bar}    <-- 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"
{$smarty.config.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}
{$foo.$bar.$baz}
{$foo[4].baz}
{$foo[4].$baz}
{$foo.bar.baz[4]}
{$foo->bar($baz,2,$bar)} <-- passing parameters
{"foo"}       <-- static values are allowed

{* display the server variable "SERVER_NAME" ($_SERVER['SERVER_NAME'])*}
{$smarty.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=$bar+2}
{$foo = strlen($bar)}               // function in assignment
{$foo = myfunct( ($x+$y)*3 )}       // as function parameter 
{$foo.bar=1}                        // assign to specific array element
{$foo.bar.baz=1}                    
{$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['bar']}
{$foo['bar'][1]}
{$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:

{$object->method1($x)->method2($y)}

Direct PHP function access:

{time()}

{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>
{else}
    hi, {$name}
{/if}

{include file="footer.tpl"}

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

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

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.

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

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

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

$smarty->assign('foo', 'bar');
$smarty->assign('name', 'Albert');
$smarty->display('example.tpl');
?>

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:

{$comobj->GetDailyBrewImage($DailyBrewArr[0].vPath,$DailyBrewArr[0].iDailyBrew,'image','didyouknow','2')}

Smarty filter / modifier:

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