Getting Started With Smarty Template Engine


 Getting Started With Smarty Template Engine  
 

“Smarty” is one of the most popular template engine available for php developers. At the beginning level of its development, it was part and sub project pf PHP and its web contents was hosted on “smarty.php.net” sub domain. Later on it itself became an independent open source project and started being on its own website: http://www.smarty.net/ . Till now, several big sites and third-party projects are using smarty as their template engine. Today, in this smarty template engine tutorial, I will try to demonstrate its basics usage in web development and few most commonly used syntax examples.

Why Template Engine :

You, like most of the beginners, might have the question in mind that, why we will use a template engine where all its tasks can be done by HTML and PHP itself? Well, sure, there are some important benefits like some as follows:

  • Encourages For Layered Structure: Being different from core PHP, it encourages developers to create layers for their application where template engine will be on the presentation layer and has only presentation logic.
  • Reducing unnecessary reproducing codes: Template Engine provides some ready-made easy integration of many presentation level features, which helps us away from trying to implement them by ourselves thus saves time to reinvent the wheel.

Why Choose Smarty Template Engine?

Actually, I haven’t learned/experienced any other PHP template engine other than smarty yet. However, while learning, like all others, i also had the question in my mind whether it’s a good decision to use smarty or not. I did some research on internet and found this one to get most votes. However, you can also find out a useful article about comparison of smarty with other template engine.

Download And Installing Smarty Library:

Download the latest version of smarty from the official site. copy the ‘smarty’ directory to you application proper place(where you usually put the third-party libraries). Now, to be able to use this in our project, we will need to set some settings first. Such as cache directory path, config directory path, template root path etc. Best way to use a custom class that will initialize this settings. Following the is code for this customized class:

if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once(APPPATH.'libraries/smarty/Smarty.class.php');

/**
 * MySmarty Class
 *
 * initializes basic smarty settings and act as smarty object
 *
 * @final	Mysmarty 
 * @category	Libraries
 * @author	Md. Ali Ahsan Rana
 * @link	http://codesamplez.com/
 */
class Mysmarty extends Smarty
{
 
    /**
     * constructor
     */
    function __construct()
    {
        parent::__construct();        
        $this->template_dir = APPPATH."/views/";
        $this->config_dir = APPPATH."/conf/";
        $this->compile_dir = APPPATH."/cache/";
	$this->caching = 0;       
    }
}

Now we are completely ready to use this custom class to our application.

Smarty Template Engine In Action:

First Thing you will have to know that, smarty uses .tpl files for its template files. So, for a better experience, checkout whether your IDE supports these file extension. If you are using Netbeans as your idea, better to install the ‘smarty plugin’ for Netbeans to get supports for not only tpl file, but also will provide smarty function’s intelligence support. Lets code for a very basic smarty base example:

Following is the PHP code on backend/controller/business logic layer:

// create an smarty object of our customized class
$smarty = new Mysmarty ;

// basic assignment for passing data to template file
$smarty->assign('title', 'Test Title');
$smarty->assign('description', 'Test Description');

// show the template
$smarty->display('index.tpl');

The ‘assign’ method takes 2 arguments, first one is the name with the variable name of template file, second one is the original data/PHP variable whatever you want to pass as the value. The ‘display’ method loads the template file that is being passed to it.

Now the template file should be the ‘index.tpl’ in ‘view’ directory which has the following template code:

<html>
<head>
<title>Info</title>
</head>
<body>
Test Article:
Title: {$title}
Description: {$description}
</body>
</html>

“{}” is the main delimiter for smarty template. every variable in template file should be bound with this delimiter.

Most commonly used syntax examples:

Besides showing the variable data received from php, smarty can also offer opportunities of using some logical block like condition, loop, generating html element and populating with backend data etc. Following are some most commonly used syntax:

//If condition
{if $name eq "smarty"}
 <span>Its smarty</span>
{/elseif $name eq "php"}
 <span>Its php</span>
{/else}
 <span>Its neither smarty nor php</span>
{/if}

//foreach loop
{foreach $articles as $article}
<h2>{$article->title}</h2>
<p>{$article->description}</p>
{/foreach}

//section, alternative of foreach
{section name=name loop=$items}
  id: {$items[name]}<br />
{/section}

//generate select option easily
{html_options values=$id output=$items selected="2"}

References :

There are some official note of smarty also , which you can use for further details.

Hope this smarty template engine tutorial will help you in some extent to get started. I will try to add more smarty tutorials in future. Feel free to ask if you have any questions. Happy Coding :)

Trackbacks

Leave a Reply