Introduction To Templating in PHP with Smarty
Smarty is a templating engine for PHP, it's one of the most popular templating engine used by PHP developers. Using a templating engine helps businesses separate presentation logic & application logic.
Templating, you can say is a way to separate the business logic from the presentation logic. Most of the world's we application developers use either embedded scripting languages like PHP, JSP, ASP etc. while other use print statements in the scripting languages to output their HTML to the world. Templating can be overlooked for small pages and websites, but as your business logic becomes complex and you starting getting more hits, maintenance and upgradation becomes tough.
A templating system allows the designer to write their own HTML with special commands/placeholders in it for the programmer to integrate the business logic into it, thereby making each others lives easier.
PHP being a embedded scripting language enabled developers to embed PHP code inside HTML files, which was very easy at a certain level, but as projects/requirements grew managing changes in layout (presentation logic) became tough & tiresome, so templating engines came to the rescue, they allow the designer to work without worrying about how the developer will display the data etc. all the designer needs to do it to use a combination of standard HTML tags, template tags & variables.
So, one day if the need arises for the layout to be completely changed there would not be any need for the developer to change his application logic, inversely if the developer needs to change the way data is fetched & processed it would not require any intervention of the designer.
Smarty is very fast, and efficient because the PHP parser does all the parsing, and the overhead is greatly reduced as the template is compiled & cached on the first run and Smarty smartly recompiles a template only if there are any modifications in the template.
Logical constructs like if, elseif, etc. help writing basic logic in the template itself. Smarty allows you to create your own custom functions & variable modifiers easing out a lot of coding on the developers' end.
There are many more small & tiny useful features which we'll discuss in upcoming articles, here we'll just go through basic usage of Smarty.
Smarty require PHP 5.2 & above, for installation instructions & details please refer to the amazingly documented Smarty documentation here.
Follow the basic demo below to understand the basic usage of Smarty, I have added commented wherever required. We'll get deeper into Smarty in another article, till then explore your imagination.
The template file:
The PHP code using Smarty:
Finally the output looks like this:
|All times are GMT +5.5. The time now is 05:03.|