CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Development Getting Started With Smarty Template Engine

Getting Started With Smarty Template Engine

Rana Ahsan May 21, 2011 8 Comments


 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.

  • Smarty Sample Application
  • Smarty Crash Course

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 🙂

Related

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

About Rana Ahsan

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

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

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.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Facebook C# API Tutorials
  • LinQ To SQL Database Update Operations In C#
  • Using Supervisord Web Interface And Plugin
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • Utilizing Config File In C#.NET Application
  • Using GIT Plugin For Netbeans IDE

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2022 · CodeSamplez.com ·

Copyright © 2022 · Streamline Pro Theme on Genesis Framework · WordPress · Log in