Smarty templates for beginners
January 21st, 2007 by morning
Note: I started to write this article a year and a half ago. I finally decided to finish it and create series of posts which will cover some Smarty tips and tricks and writing plugins and modifiers.
THE PROBLEM: PHP and HTML-embedded PHP
As PHP is HTML-embedded scripting language you can easily nest php code inside html and get dynamically generated page. Great, isn’t it? Yes, as long as you know what you are doing. The trouble comes when programmers and designers start to work together on the same project. In that case programmers should try to ‘hide’ their code as much as possible from designer’s eyes, not only because designers doesn’t like to see bunch of weird signs between their HTML, but because they can easily remove a single semicolon and cause parse error in PHP. This result in arguments and blaming who erased what (for solving this you should also consider using code versioning: CVS or Subversion). Let’s see few examples.
[code]
$var = "Hello World";
?>
echo"
echo $var;
echo “
“;
?>
[/code]
Looks pretty neat, right? You are asking yourself, why is this bad. It isn’t if we stay on this stage of simplicity.
What if we need to display data we fetched from database within an html table?
[php]
//db configuration inclusion
include "config.php";
if(!($db = @mysql_connect(BASE_SERVER, BASE_USER, BASE_PASS))) //connect to base host
die("Cannot connect to the base server.");
if(!@mysql_select_db(BASE_NAME, $db)) //select base
die("Database doesn't exist!");
$sql = "SELECT * FROM users";
if(($result = @mysql_query($sql, $db)) == 0)
{
echo "\n
Database error: “.mysql_error().”
\n”;
die(”Query was ($sql) in file $_SERVER['PHP_SELF']“);
}
$user = array();
?>
| Name | Lastname | ||
| Name | Lastname | |
[/php]
This definitely looks much better. The way it is now, designers doesn’t even need to look at example.php and don’t care what’s in it. As long as he doesn’t touch what is between open and close php tag, everybody is happy.
One more advantage of templates is that we can include template within a template. This way we don’t need to repeat the same code over and over again on different pages. For example, we can separate header and footer of the page into new files and just include them into our example-2.tpl.php.
SOLUTION 2: SMARTY TEMPLATE ENGINE
I won’t go into discussion why some developers like and why some dislike Smarty template engine. First time when I got in touch with it, which was back in 2002., I didn’t want to accept it, it looked to complex and not necessary. It took me a month to realize it that I won’t be able to live without it :).
Smarty offers that you separate your code as much as possible from presentation with a easy-to-learn syntax for both programmers and designers.
In the next example I will show you how to convert example-2 to work with Smarty.
First of all, download latest stable version of Smarty. Once you downloaded it, extract it into temporary dir.
Next thing to do is to setup all directories and files Smarty needs. It requires templates, templates_c, cache and configs directories. Templates dir should be used to place templates you create, templates_c is directory is for complied templates, cache for cached templates and configs for config files. However, you can name them however you want, but make sure you tell Smarty that. I created one more directory named smarty, where you should copy libs directory which comes along with archive you just downloaded.
At this point, you should have structure of your future web app like this:
[cache]
[configs]
[smarty][libs]
[templates]
[templates_c]
Make sure to make templates_c and cache directory writable by your web server
I have created one more directory entitled includes where I’m going to put config file which will contain some basic configuration such as database info as well as some code which will be used for initializing Smarty.
Here is the code within config.php file:
[php]
//db configuration
define ("BASE_SERVER","localhost");
define ("BASE_USER","root");
define ("BASE_PASS","");
define ("BASE_NAME","test");
/*******************
SMARTY
*******************/
require_once("smarty/libs/Smarty.class.php");
$smarty = new Smarty;
?>
[/php]
If you decide to rename directories such as templates and templates_c, make sure to add those lines, too, like this:
[php]
$smarty->template_dir = “path_to_your_template_dir”;
$smarty->compile_dir = “path_to_your_compile_dir”;
[/php]
Now, lets modify our latest example file to work it with Smarty.
example.php:
[php]
//db configuration inclusion
include "includes/config.php";
if(!($db = @mysql_connect(BASE_SERVER, BASE_USER, BASE_PASS))) //connect to base host
die("Cannot connect to the base server.");
if(!@mysql_select_db(BASE_NAME, $db)) //select base
die("Database doesn't exist!");
$sql = "SELECT * FROM users";
if(($result = @mysql_query($sql, $db)) == 0)
{
echo "\n
Database error: “.mysql_error().”
\n”;
die(”Query was ($sql) in file $_SERVER['PHP_SELF']“);
}
$user = array();
while($tmp = mysql_fetch_assoc($result))
{
$user[] = $tmp;
}
$smarty->assign(”title”, “Example with Smarty”);
$smarty->assign(”user”, $user);
$smarty->display(”example.tpl.htm”);
?>
[/php]
As you can see, only difference are last 3 lines of code. First one is assigning some string to variable title, second one is assigning content of array $user and the last one tells smarty to display example.tpl.htm file.
At this point example.tpl.htm looks like this and it is placed within templates directory:
[html]
{include file=”header.tpl.htm”}
| No | Name | Lastname | |
| {$smarty.section.c.iteration} | {$user[c].Name} | {$user[c].Lastname} | {$user[c].Email} |
{include file=”footer.tpl.htm”}
[/html]
As you may notice, on first line, I am including file header.tpl.htm and on the last one footer.tpl.htm. {include} tags are often used for including other templates files in the current template. All variables which are available in our current template are available for included templates as well. This example demonstrates it with $title var.
header.tpl.htm at this point looks like this:
[html]
[/html]
Footer.tpl.htm
[html]
[/html]
In the example.tpl.htm our initial for loop turned into
[php]
{section name=c loop=$user}
{/section}
[/php]
{section} is for a looping over arrays of data and each of section tags must be followed by closing tag {/section}. {section} tag requires only two attributes: name and loop. Name attribute is a name of the section and loop is a value to determine the number of loop iterations. However, {section} has other optional attributes such as start, step, max, show. I will those to you to investigate their purpose.
{section} also has its own variables which handle section properties. One of them I used to show the numer of iteration and it is echoed with {$smarty.section.c.iteration}.
Also, you are able to nest sections within sections, however, make sure that you name those differently.
This is it, Smarty in some basic action. This code only shows how to install and use some basic options. There is so much to smarty, and I will try to show you how to use modifiers, write your own and to take advantage of everything smarty offers.
Here you can download all code I used in my examples.
So, enjoy it. :)
- Posted in Programming, Smarty, Web development

15 Responses to “Smarty templates for beginners”
Once I get time to try out smarty, I will have your article right next to me!
Jelena, your such a smarty :D
Good article, jelly. You da man. :cool
I don’t really see how Smarty is better ‘creating your own template system’ (solution 1). I mean, with the ‘own’ template, the designer would need to learn some PHP commands and with the Smarty template, he would need to learn the Smarty commands.
In both cases, he should probably not touch the PHP/Smarty-code and if he does, it will be equally messy.
Furthermore, in PHP it would be possible to use foreach, which would remove the need for some counter variable. Also, the shorthand could be used to make the PHP less verbose.
I don’t really see the need for templating engines, because PHP is basically a templating engine itself!
Jordi I’ve worked with a lot of designers and HTML coders. They all agree that Smarty syntax is much easier for them to grasp - more importantly they are less afraid to use it, since they know that there is a safety net (i.e. they cannot break anything except template).
From programmers point of view separated template system is a good thing for the same reason. You provide designers a sandbox in which they can play without any danger for rest of the program.
Additionally, there’s a reason why people are pushing stuff like MVC frameworks (Model-View-Controller) and using separate template engine forces you to use at least the view component. Otherwise, sooner or later, you’ll be tempted to mess around with data in templates - and that’s a bad thing.
Basti has a very good point.
One more thing, you can, in fact, user foreach in Smarty as well. I used for loop, just do demonstrate the smarty syntax.
cool… a’m actually working with the new projects of our company… and using smarty is good, it’s another programming etiquette… much organized and more understandable both to programmers and designers.
[...] I already wrote small tutorial for beginners which covers installation and some common usage of smarty tags. [...]
cool… a’m actually working with the new projects of our company… and using smarty is good, it’s another programming etiquette… much organized and more understandable both to programmers and designers.
regards
I love the “provide designers a sandbox in which they can play”.
This is exactily the best point about it, the mess can heappens as using just php, no problem.. but the PHP (that is the most important) is not touch, so really nice.
Who plays with .net aplications nows exactily what is to programm in 3 steps DATABASE+CODE+HTML CODE, they love it because is exactily the same thing that Smarty do for PHP.
If you check, PHP is at this momment the best internet programm language. It’s fast, now haves template and with PHP 5, the PHP gots respect in the OOP world. Is 100% complete.
I love PHP + SMARTY
thanks for a simple but great article. Why oh why did I only hear of Smarty today?? I am going to try this out asap.
Best wishes from Ireland.
Hi, Thanks for such a good article.Its very beneficial for smarty biginners.
I just got a cms that uses smarty and It’s not complicated it just takes getting used to. I like using php and after studying php for a year now I have to learn how to write smarty template codes, which has a whole lot of different attributes to it that I have to learn. WTF. There are articles for writing a basic templating system for php. I have to agree with Jordi. I think a lot of cms’s use smarty because it’s free. It’s like md5ing a sha1.
A wonderful article indeed. Thanks :)
It’s a really good way to design a sequre and
smart website.
Syntax and way of programming is better and
easily understandable.
by: Pradeep
Have something to say?