Ransford Okpoti's Dev Notes

October 23, 2008

Smarty Templating Overview

Filed under: PHP,Smarty — Tags: , , — admin @ 12:39 pm

Smarty is one of the most popular PHP templating engines. There are many other templating engines, based on similar principles, such as

  • PHPTemplate
  • PHPTAL (TAL Template Attribute Language), phptal.motion-twin.com/
  • Savant, http://phpsavant.com/
  • FastTemplate
  • PHPlib

Irrespective of the templating engine that one uses, one of the design goals is the separation of business logic from the presentation logic. A point of caution, you can still use Smarty, the wrong way, without the clear separation of the business and presentation logic since Smarty does not enforce the separation of the 2 logics.

Business logic basically has to deal with how you solve the problem at hand, such as the computation of an employee’s monthly salary using the various parameters required in a typical payroll application.

Presentation logic, as the name suggests, deals with the logic pertaining to the presentation of data/content only. Examples of presentation logic are: iterating through an array of data to be displayed, picking the first X number of characters to display such as displaying a news or an article summary, alternating row colours of tables, etc.

Simply put, a templating engine replaces placeholders with values you specify.
In a real world web development project, there are going to be 2 main teams working on the project namely:
The developers/programmers who uses the full power of the programming language to achieve the requirements of the system such as accessing data from a database or a web service, validating and process the data, and persisting or presenting the processed data if required.
Designer or user interface (UI) team which builds the interface the users of the application would interact with using xHTML and it’s various controls or any appropriate UI technology suitable for the project at hand without affecting the developers codes.

SMARTY INSTALLATION

  1. Grab a copy of the smarty templating engine from http://smarty.net/download.php, as at the time of writing this article the latest stable version is 2.6.19. Extracting the content of the downloaded compressed file gives you this structure:
    Smarty-2.6.19/
      demo/
      lib/
      misc/
      unit_test/
      …
  2. Create a lib folder in your site where all libraries will be kept.
  3. Within the lib folder create a folder with the name smarty and copy the libs folder of the extracted file here.
  4. Now, create these 4 folders
    • templates, all template files, normally with the extension .tpl, goes into this folder
    • templates_c, compiled versions of all the templates will automatically be place here for you by smarty
    • configs, configuration files goes here
    • cache, directory/folder for cache files

After the installation, the directory structure for your project/site must be something like this

root_of_site/
  cache/
  configs/
  lib/
  smarty/
  libs/
  templates/
  templates_c/

After the installation, it is recommended that you subclass the Smarty class itself as this gives you the chance to modify some of the default settings of smarty and apply project specific settings here. Now, lets create a file with the name CustomSmarty.class.php in the site’s root folder ie. /root_of_site/CustomSmarty.class.php

<?php
    set_include_path( get_include_path().PATH_SEPARATOR.'./lib');
    require_once('Smarty/libs/Smarty.class.php');
    if(!defined('REQUIRED_SMARTY_DIR')) define('REQUIRED_SMARTY_DIR','./');	

    class CustomSmarty extends Smarty{

        function __construct(){
            $this->Smarty();

            /*
            You can remove this comment, if you prefer this JSP tag style
            instead of the default { and }
            $this->left_delimiter =  '<%';
            $this->right_delimiter = '%>';
            */

            $this->template_dir = REQUIRED_SMARTY_DIR.'templates';
            $this->compile_dir 	= REQUIRED_SMARTY_DIR.'templates_c';
            $this->config_dir  	= REQUIRED_SMARTY_DIR.'config';
            $this->cache_dir   	= REQUIRED_SMARTY_DIR.'cache';
        }
    }
?>

Now let’s create our template file with the name index.tpl into the templates folder.
Note that all the elements in the tag { } will be substituted in our code.
index.tpl

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Smarty Demo</title>
  </head>

  <body>
    {$msg} <br/>
    <!-- Applying a modifier -->
    {$msg|upper} <br/>

    Select a country:
    <select name="select">
      {html_options options=$countries selected=$selectedCountry}
    </select>
    <p/>
    <!-- For dynamically generated options, it comes in handy -->
    {html_checkboxes values=$country_keys output=$countries
    selected=$selectedCountries separator='<br/>'}
    <p/>

    <!--
I wouldn't recommend you use the date component provided by Smarty since
it's not visually appealing and offers no validation whatsoever
    -->
    Day of departure: {html_select_date start_year="-10"} <br/>
    Time of departure: {html_select_time}

    <p/>
    <!--
{$flight->company} replaces <?php echo $flight->company; ?> you would have to use
if you weren't using Smarty
    -->
    <form id="form1" name="form1" method="post" action="">
      Flight: <input  type="text" id="company" value="{$flight->company}" />
      <br/>
      From: <input type="text" id="from" value="{$flight->from}" />
    </form>

    <p/>
    <table width="100%" cellpadding="0" cellspacing="0">
      <tr align="left">
        <th width="18%" scope="col">SSN</th>
        <th width="25%" scope="col">COURSES</th>
        <th width="14%" scope="col">CREDITS</th>
        <th width="21%" scope="col">SCORE</th>
        <th width="22%" scope="col">COMMENT</th>
      </tr>
      {section name=c loop=$courses }
      <tr bgcolor="{cycle values='#FFA, #FFF'}">
        <td>{$smarty.section.c.iteration}</td>
        <td>{$courses[c].name}</td>
        <td>{$courses[c].credit}</td>
        <td>{$courses[c].score}</td>
        <td>
          {if $courses[c].score gte 50}
          PASS
          {else}
          FAIL
          {/if}
        </td>
      </tr>
      {/section}
    </table>
    <p/>

    <!--
Modifiers can be used to change the output of the passed variable by
doing some processing on it first such as displaying a date in a specified
format.
    -->
    Created on: {$posted|date_format:"%A, %B %e, %Y"}
  </body>
</html>

Next, create a PHP file with the name index.php in the site’s root folder ie. /root_of_site/index.php

<?php
    include_once('CustomSmarty.class.php');

    class Flight{
        public $company;
        public $from;
        public $to;

        public function __construct(){
            $this->company = 'South African Airways';
            $this->from = 'Accra';
            $this->to = 'London';
        }
    }

    $lsCourses = array(
        array('name'=>'Programming using BASIC', 'credit'=>2, 'score'=>70),
        array('name'=>'XMLifying data', 'credit'=>1, 'score'=>40),
        array('name'=>'Web 2.0 Concept', 'credit'=>2, 'score'=>49)
    );

    $countries = array(
        'gh' => 'Ghana',
        'ng' => 'Nigeria',
        'lr' => 'Liberia',
        'ch' => 'China'
    );
    $smarty = new CustomSmarty();
    $smarty->debugging_ctrl = URL;

    $smarty->assign('msg', 'This is a demonstration of the Smarty templating engine.');
    $smarty->assign('countries', $countries);
    $smarty->assign('country_keys', array_keys($countries));
    $smarty->assign('selectedCountry', 'lr');
    $smarty->assign('selectedCountries', array('lr'));
    $smarty->assign('flight', new Flight());
    $smarty->assign('courses', $lsCourses);
    $smarty->assign('posted', '2008-08-27');

    $smarty->display('index.xhtml');
?>

I used smarty_demo as the site root.
Pointing your browser’s URL to http://localhost/smarty_demo, you should see the outcome displayed below.

Smarty demo screen capture

Smarty demo screen capture

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Twitter

4 Comments »

  1. nice tut man i gonna try out i did before but i was stuck
    i will try this one and let you know thanks bye see you
    i love you site can i you give me the template just to chech how it was made thanks
    bye
    regards
    peace
    angell

    Comment by PEACE — July 6, 2009 @ 8:54 am

  2. Don’t hesitate to get back to me, if you face any difficulties. For the template, search for Velocity on http://www.blogohblog.com/

    Comment by admin — July 6, 2009 @ 12:14 pm

  3. nice one. gonna try out smarty.

    Comment by wong yu liang — October 12, 2009 @ 10:04 am

  4. Thanks.

    Comment by admin — October 12, 2009 @ 10:30 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

Spam protection by WP Captcha-Free

Powered by WordPress