
“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 content was 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 of the 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 HTML and PHP can do all its tasks? Well, sure, there are some important benefits like as follows:
- Encourages For Layered Structure: Being different from core PHP, it enables 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 ready-made, easy integration of many presentation-level features, which helps us avoid trying to implement them ourselves, thus saving time reinventing 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 helpful 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. The best way to use a custom class is to 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 https://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 in 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, it is better to install the ‘smarty plugin’ so that Netbeans can get support not only for the “tpl” file but also for the smarty function’s intelligence support. Let’s code for an elementary 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 two arguments: the first one is the name with the variable name of the template file, and 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 and loops, generating HTML elements, populating with backend data, etc. Following are some of the 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 also an official note about Smarty, which you can use for further details.
I hope this smarty template engine tutorial will help you get started to some extent. I will try to add more Smarty tutorials in future. Feel free to ask if you have any questions. Happy Coding 🙂
Discover more from CodeSamplez.com
Subscribe to get the latest posts sent to your email.
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.