
“Smarty” is one of the most popular template engines available for PHP developers. At the beginning of its development, it was part and sub-project of PHP and its web contents were hosted on the “smarty.php.net” subdomain. Later on, it became an independent open-source project and started on its 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 basic usage in web development and a few most commonly used syntax examples.
Why Template Engine :
You, like most beginners, might have the question in mind, why will we use a template engine where all its tasks can be done by HTML and PHP itself? Well, sure, there are some important benefits like as follows:
- Encourages For Layered Structure: Being different from core PHP, it encourages developers to create layers for their application where the 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 saving time to reinvent the wheel.
Why Choose Smarty Template Engine?
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 was a good decision to use smarty or not. I did some research on the internet and found this one to get the most votes. However, you can also find out a useful article about the comparison of smarty with other template engines.
Download And Installing Smarty Library:
Download the latest version of smarty from the official site. copy the ‘smarty’ directory to your application’s 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 setting. 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;
}
}
Code language: PHP (php)
Now we are completely ready to use this custom class to our application.
Smarty Template Engine In Action:
The first thing you will have to know is that, smarty uses .tpl files for its template files. So, for a better experience, check out whether your IDE supports these file extensions. If you are using Netbeans as your idea, better to install the ‘smarty plugin’ for Netbeans to get support for not only tpl file but also will provide smarty function’s intelligence support. Let’s code for a very basic smarty base example:
Following is the PHP code on the 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');
Code language: PHP (php)
The ‘assign’ method takes 2 arguments, the first one is the name with the variable name of the template file, the 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>
Code language: HTML, XML (xml)
“{}” is the main delimiter for the smarty template. every variable in the 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 for using logical blocks like conditions, loops, generating HTML elements 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"}
Code language: PHP (php)
References :
There is some official note of smarty also, which you can use for further details.
I hope this smarty template engine tutorial will help you to 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 🙂
Nice tutorial Ali Ahsan Rana. I like your code in Codeiginter. I also see your Codeiginter plus functionality and CRUD system. That is amazing. Thanks for sharing information.
Thanks bro really useful.
Hi, I am new to smarty and php. I have a query where do you create a smarty object for customized class? is it separate file? and as per your example $smarty->display(‘index.tpl’), is index.tpl is the file where you are going to show these variables (title and description)?
Thanks
It’s nice, I get the lot of information in the site
Thanks to you
hi used smarty. i dont know where this error coming from.MDB2 error: insufficient permissions
can u help me??
Hi
I am new to smarty .
I am getting an error on homepage of mysite. MDB2 error insuffisient permissions.
can anybody help me??
Thanks for your post. I have a question though, how do i use smarty to convert html to tpl that can be hyip compatible? Thanks.