Jump to content

PHP Programming/Smarty templating system

From Wikibooks, open books for an open world

What is Smarty?

[edit | edit source]

Smarty is a templating engine for PHP. It allows you to separate logic and presentation by separating the PHP code from the HTML (or anything else for that matter) presentation[1].

Old/custom templating engine example

[edit | edit source]

It is just like below: (The code below is a demo of a custom template engine - not Smarty)

There are two files here "mail.html" (we can say this is a template file) and "mail_engine.php" (ya, you are right...it is an engine.)

mail.html
 <html>
 <body>
 <h1>My company name is #COMPANY#</h1>
 <p>
   Please note our address #ADDRESS1#, #ADDRESS2#, #CITY#-#PIN#.
   Contact us on #PHONE#.
 </p>
 <p>
  Hope you like my mail.
 </p>
 <p>
  Thanking You,
 </p>
 <address> Jaydeep Dave, +919898456445, jaydipdave@yahoo.com </address>
 </body>
 </html>
mail_engine.php
<?php
 $contents = file_get_contents("mail.html");
 function rtemplate(&$tdata,$vars)
 {
   $nv = array();
   foreach($vars as $key => $value)
   {
     $kk = "#".strtoupper($key)."#";
     $nv[$kk] = $value;
   }
   unset($vars);
   $tdata = strtr($nv,$tdata);
   return true;
 }
 $vars = array(
   "company" => "Premier Business Softwares&quot",
   "address1" => "XXXXXXXXXXX",
   "address2" => "XXXXXXXXXXX",
   "city"=>"bHAVNAGAR",
   "pin"=>"364001",
   "phone"=>"+919898456445"
 );
 rtemplate($contents,$vars);
 echo $contents;
?>

This example allows small functionality. You might have big problems if your company value contains #CITY#, for example. There are much more advantages of using smarty. But anyway, raw PHP templating is most effective and fastest.

How does it work?

[edit | edit source]

Smarty is a template engine which actually compiles the template file to the php file that can be later executed. This simply saves time on parsing and variable outputs, beating other Template Engines with much smaller memory use and regex.

Installation

[edit | edit source]

Installation is very basic and easy to use

  1. Download Smarty Source from smarty.net
  2. Open it using your archive extractor (must be compatible with .tar.gz files)
  3. Go to the directory called Smarty-x.x.x
  4. Copy the libs folder to your website's root ( where you want the website to exist, for example /My_Site/ )
  5. You are done!

There is no requirement to copy other files as they are simple examples.

Usage

[edit | edit source]

Simple example

[edit | edit source]
<?php
     $abc = 'hello ';
     $smarty->abc("abc",$abc);
?>
{$abc}

Basic Syntax

[edit | edit source]
 {* Sample Smarty Template *}
 
 {* Include a header file *}
 
 {* Include a file from a variable $header_file, which is defined by the php script *}
 {include file=$header_file}
 {include file="middle.tpl"}
 {* Simple alternative to PHP's echo $title;
 {$title}
 {* Include a file from a variable #footer#, which is defined by the config file *}
 {include file=#footer#}
 
 {* display dropdown lists *}
 <select name="company">
 {html_options values=$vals selected=$selected output=$output}
 </select>
 {*end*}

Basic Syntax #2

[edit | edit source]

Comments:

{* Comment *}

Writing a variable, assigned from the PHP script:

{$variable}

Writing a variable, assigned from the config file:

#variable#

Using a variable in a function:

$variable

Other Examples (Smarty Documentation):

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

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

Calling Functions:

{function}

Integrating into a website

[edit | edit source]

To make use of the Smarty Template engine you will need to change your php script, which is used for controlling the Smarty engine and compile the template file. Simple example:

<?php
 // Include Smarty Library
 require_once("libs/Smarty.inc.php");
 // Create new variable $smarty from the class Smarty
 $smarty=new Smarty();
 // Set the template directory, very useful for different templates
 $smarty->template_dir="templates";
 // From here you should put your own code
 // Set some variables
 $smarty->assign("Title"=>"Just a test");
 // Create an array, which we will assign later
 $contacts=array(
   array("Name"=>"John Parkinson","email"=>"john.parkinson.test@domain.tld","age"=>26),
   array("Name"=>"Super Mario","email"=>"super.mario@domain.tld","age"=>54),
   array("Name"=>"Pete Peterson","email"=>"pete.peterson@domain.tld","age"=>18),
   array("Name"=>"Smarty Creator","email"=>"smarty.creator@domain.tld","age"=>37)
 );
 // Assign the array
 $smarty->assign("contacts",$contacts);
 // Compile and Display output of the template file '''templates/index.tpl'''
 // Up to here you should put your own code
 $smarty->display("index.tpl");
?>

Variables

[edit | edit source]

#Basic Syntax #2

Arrays

[edit | edit source]

Please refer to #Variables

Looping

[edit | edit source]

Looping in smarty is just like PHP, except that there are different ways of approaching the variables. For example, in PHP you would write this:

 foreach($array as $key => $value) {
    echo "$key => $value\n";
 }

As Smarty compiles similar piece of code by this:

 {foreach from=$array key="key" item="value"}
 {$key} => {$value}
 {/foreach}

Also, you can use a section function which is very similar to foreach

In the case the designer wanted to add bullet points, or indexes of the array items, there would be no need to do anything for the programmer as you can use other variables that would change themselves after each loop.

Conditions

[edit | edit source]

{if} statements in Smarty have much the same flexibility as PHP if statements, with a few added features for the template engine. Every {if} must be paired with an {/if}. {else} and {elseif} are also permitted. All PHP conditionals are recognized, such as ||, or, &&, and, etc.

The following is a list of recognized qualifiers, which must be separated from surrounding elements by spaces. Note that items listed in [brackets] are optional. PHP equivalents are shown where applicable.

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

References

[edit | edit source]
  1. Smarty Website, Documentation, Downloads