• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / Getting Started With Smarty Template Engine

Getting Started With Smarty Template Engine

May 21, 2011 by Rana Ahsan 9 Comments

PHP Smarty Tutorial

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

  • Smarty Sample Application
  • Smarty Crash Course

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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: php, smarty, web application

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. Chintan Panchal says

    September 1, 2015 at 12:25 pm

    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.

    Reply
  2. abugasiem says

    October 18, 2015 at 10:42 pm

    Thanks bro really useful.

    Reply
  3. Kapil says

    November 16, 2015 at 4:27 am

    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

    Reply
  4. rajaram says

    March 7, 2016 at 1:41 am

    It’s nice, I get the lot of information in the site

    Thanks to you

    Reply
  5. vishal says

    March 24, 2017 at 11:49 am

    hi used smarty. i dont know where this error coming from.MDB2 error: insufficient permissions
    can u help me??

    Reply
  6. vish says

    March 24, 2017 at 2:36 pm

    Hi

    I am new to smarty .

    I am getting an error on homepage of mysite. MDB2 error insuffisient permissions.

    can anybody help me??

    Reply
  7. Precious says

    November 23, 2022 at 6:51 pm

    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.

    Reply

Trackbacks

  1. Using Smarty With Codeigniter | codesamplez.com says:
    June 7, 2011 at 1:51 am

    […] With Codeigniter Posted on June 7, 2011 Tweet Before, I have written tutorials about smarty basics as well as codeigniter basics. Today, in this tutorial, i will try to guide you through how to […]

    Reply
  2. Guidelines And Best Practices For Codeigniter Development | codesamplez.com says:
    November 17, 2011 at 2:19 am

    […] on codeigniter. If you are very new to smarty, then you can consider reading my earlier article on getting started with smarty . Also, if you have some basic idea, but looking for integrating it on codeigniter, you can read […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Getting Started With Smarty Template Engine
    Getting Started With Smarty Template Engine
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • LinQ To SQL Database Update Operations In C#
    LinQ To SQL Database Update Operations In C#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023