Introduction to the Smarty Templating Framework

Introduction to the Smarty Templating Framework

Tutorial Details
  • Program: Smarty
  • Version: 3.0 RC3
  • Difficulty: Easy
  • Estimated Completion Time: 30 minutes

Smarty is a PHP-based templating engine/framework. It allows you to further separate your business logic from its visualization, by removing as much PHP code as possible away from your views. Some developers and frameworks prefer not to use a templating engine, others do prefer them to using plain PHP in your views. Both points of view can be argued, and in the end, it’s mostly a matter of taste. Anyway, it’s never a bad idea to try it out before deciding not to use it, and that’s what this tutorial is about: trying out the Smarty Templating Framework.


Step 0: What To Expect

At the end of this tutorial, you’ll have a basic idea of how Smarty works. You’ll be able to load template files, pass variables to them, use a “layout” in which your other views are inserted, and write your own modifiers. This will all be accomplished using an additional wrapper class, which you can easily integrate in your existing projects.


Step 1: Setting Up The Project

The project for this tutorial will have a very easy setup, since we’re not developing a real application. Just create a project folder (mine is named “smarty_example”) with an index.php file in it, and a directory called “lib” inside of it. Also, create a file named smtemplate.php in the “lib” folder. Next, create a “views” folder inside “smarty_example”. This folder will contain our smarty template files.

Before you’re able to use something, you have to install it. Thankfully, installing Smarty is extremely easy and requires almost no configuration. First of all, download Smarty and extract the archive. You can check out everything inside the archive, but we’ll only need the “libs” folder for our application. Rename it to “smarty” and paste it inside the “lib” folder of our application. Smarty uses some additional folders, so create the “templates_c”, “cache” and “configs” folders inside our “lib/smarty” folder. If you’re not using Windows, you’ll have to give 775 permissions on these folders to your webserver. Your directory tree should now look like this:


Step 2: Creating The SMTemplate Class

Every programmer has his own idea about the ideal API. In order to adjust Smarty’s API slightly, and allow us to add some additional functionality, we’ll create a wrapper class called SMTemplate, which will take care of the smarty details for us. This approach has another advantage: if, at one moment in time, you should choose to use another template engine, you can create a wrapper for that engine, while retaining the SMTemplate interface, and thus without breaking the code that uses our SMTemplate class.

Storing Your Configuration

Before coding the SMTemplate class functionality, we’ll need a place to store some configuration details. You can do this in multiple ways, i.e. by defining config options as class constants, by defining them as constants in the smtemplate.php file, or by keeping them in a separate config file. I prefer the last option, so I’ll create an smtemplate_config.php file. Smarty needs configuration for the template, compiled template, cache, and config directories. Later, we might also add SMTemplate specific options to our config file, but for now, this will do:

/**
 * @file
 * Configuration file for the SMTemplate class
 */
 
$smtemplate_config = 
	array(
		'template_dir' => 'views/',
		'compile_dir' => 'lib/smarty/templates_c/',
		'cache_dir' => 'lib/smarty/cache/',
		'configs_dir' => 'lib/smarty/configs/',
		);

Building the SMTemplate Class

The SMTemplate class will load this config file, and pass the options to Smarty. Before we can pass the options, we’ll need an object of class Smarty. Our SMTemplate class could extend the Smarty class, but I prefer to use a private instance variable to contain the Smarty object. So far, we have the following for our SMTemplate class:

/**
 * @file
 * Wrapper for Smarty Template Engine
 */

require_once('smarty/Smarty.class.php');
require_once('smtemplate_config.php');

class SMTemplate{
	
	private $_smarty;
	
	function __construct(){
		$this->_smarty = new Smarty();
		
		global $smtemplate_config;
		$this->_smarty->template_dir = $smtemplate_config['template_dir'];
		$this->_smarty->compile_dir = $smtemplate_config['compile_dir'];
		$this->_smarty->cache_dir = $smtemplate_config['cache_dir'];
		$this->_smarty->configs_dir = $smtemplate_config['configs_dir'];
	}
}

Rendering templates

As you can see, our class is still pretty pathetic, as it can’t render anything. We’ll solve this issue by adding a render function, which loads a template and displays it.

	function render($template){
		$this->_smarty->display($template . '.tpl');
	}

In order to render anything, we’ll need to create a template file, and then call the render function from our index.php file. The template file will be pretty basic, containing a simple html page. Name it “home.tpl”, and place it inside our “views” directory.

<html>
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
		<title>Home</title>
		<link rel="stylesheet" href="/css/master.css" type="text/css" media="screen" title="no title" charset="utf-8" />
	</head>
	<body>
		<p>Hello, World!</p>
	</body>
</html>

Now, all that is left is to create an SMTemplate object and render ‘home’. Open up index.php, add the following lines of code, and navigate there in your browser.

require_once('lib/smtemplate.php');

$tpl = new SMTemplate();
$tpl->render('home');

Step 3: Assigning and Formatting Variables

If we couldn’t render anything dynamically, Smarty would be pretty useless. Luckily, we can assign variables to our smarty class, and display those in our template. We can also use some Smarty functions (well, modifiers actually) to format them the right way.

Passing an Array of Variables

Though Smarty supports the assignment of variables, our SMTemplate doesn’t (yet). We’ll provide the CodeIgniter-style of assignment, where you pass an array to the render function. You can adapt SMTemplate to support other methods as well; for example, assigning them to the object and then using __set to store them in an array is also a clean way. For this tutorial though, passing an array will do. Before assigning the variables, we’ll edit our template to something a little more dynamic. Saying hello to the world is customary for programmers, but not very useful, so let’s use a variable to determine who we’re hello-ing. Secondly, we’ll add today’s date to the message. Variables can be displayed by wrapping them in curly brackets.

<body>
	<p>Hello, {$receiver}! It's {$date} today!</p>
</body>

If you refresh the page, you’ll see that the variables haven’t been filled in, since we didn’t set them. Setting variables can be done using smarty->assign, so let’s assign them. The render function will now take an optional data array as a second argument.

function render($template, $data = array()){
	foreach($data as $key => $value){
		$this->_smarty->assign($key, $value);
	}
	$this->_smarty->display($template . '.tpl');
}

It still won’t work, because we don’t pass in an array when calling our render function. We can easily do this, by altering a few lines in our index.php file.

$data = array(
	'receiver' => 'JR',
	'date' => time(),
	);

$tpl = new SMTemplate();
$tpl->render('home', $data);

If you refresh now, the page will say something like “Hello, JR! It’s 1282810169 today!”. Of course, this date isn’t really what we had in mind. It needs to be formatted, which brings us to the next section.

Using Modifiers to Format Variables

Smarty isn’t just a template engine that searches and replaces variables. It’s also a powerful framework, that allows you to save time by using things like modifiers, functions, and blocks. If we wish to format our date, for example, we can use the date_format modifier. To apply a modifier to a variable, simply put a pipe character and the modifier name behind it, followed by the optional arguments which are separated by colons. The date_format modifier takes a string argument, which represents the format the date will take, and an optional default date, which we won’t need. The following code will display the date as “day (in decimals) Month”.

<body>
	<p>Hello, {$receiver}! It's {$date|date_format:"%d %B"} today!</p>
</body>

This should now give something of the form “Hello, JR! It’s 26 August today!” Now, maybe we want to make sure our receiver is uppercased. We can achieve that by using the upper modifier.

<body>
	<p>Hello, {$receiver|upper}! It's {$date|date_format:"%d %B"} today!</p>
</body>

Now, if I alter index.php to pass ‘jr’ instead of ‘JR’, the template will still show ‘JR’. Easy, isn’t it? Next, we’ll include our templates in a default “layout”.


Step 4: Working With a Layout

Before we alter our SMTemplate class to enable layouts, we’ll create a layout first. Create a new directory named “layouts” inside our “smarty_example” folder and move home.tpl there. Rename it to ‘page.tpl’. We’ll remove our previous ‘hello world’ content, and put two horizontal lines in. Our content will be placed in between these lines.

<html>
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
		<title>Home</title>
		<link rel="stylesheet" href="/css/master.css" type="text/css" media="screen" title="no title" charset="utf-8" />
	</head>
	<body>
		<hr />
		<hr />
	</body>
</html>

Of course, this won’t cut it, since Smarty won’t know where to insert our content. There is more than one way to get content from another template inside of our layout, and I’ll use Smarty’s fetch function. This function returns our template as text, instead of displaying it. This means we can fetch the template, and then assign it to a variable for use within our template! This variable’s name is yours to choose. I prefix my special variables with __, to distinguish them from the other variables I use. I’ll call this one ‘content’, since we’re assigning our page content to it.

<body>
	<hr />
		{$__content}
	<hr />
</body>

This concludes our layout, so let’s create some templates to use as content. I’ll create a ‘hello’ template, which will contain a standard ‘hello world’ line, and a ‘lipsum’ template, which holds some Lorem Ipsum text. Don’t forget to give these templates a .tpl extension.

<p>Hello, World!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean aliquet dignissim diam at vulputate. Aenean nec ligula ac dolor fringilla pharetra. Cras in augue ac tellus dictum pellentesque. Integer elementum tempus lectus, non rutrum sem viverra a. Sed tincidunt sollicitudin dolor, ut blandit magna auctor non. Maecenas sed nibh felis. Donec dictum porta ante at faucibus. Morbi massa tellus, pulvinar id porta id, imperdiet vel nibh. Donec lectus nulla, porttitor a tempor id, cursus vitae leo. Nulla eget nunc eu lorem posuere hendrerit ut ac urna. Aenean sodales lobortis egestas. Integer faucibus hendrerit tempor. </p>

Adapting our SMTemplate class to use a layout is also extremely easy. We’ll first set up a configuration option for the layouts directory, like we did for our views.

/**
 * @file
 * Configuration file for the SMTemplate class
 */
 
$smtemplate_config = 
	array(
		'layouts_dir' => 'layouts/',
		'template_dir' => 'views/',
		'compile_dir' => 'lib/smarty/templates_c/',
		'cache_dir' => 'lib/smarty/cache/',
		'configs_dir' => 'lib/smarty/configs/',
		);

Next, we’ll change our render function. We’ll supply the layout as an optional third parameter, and let it default to ‘page’. Then, we’ll fetch the requested template, assign it to the $__content variable, and display our layout.

function render($template, $data = array(), $layout = 'page'){
	foreach($data as $key => $value){
		$this->_smarty->assign($key, $value);
	}
	$content = $this->_smarty->fetch($template . '.tpl');
	$this->_smarty->assign('__content', $content);
	$this->_smarty->display($layout . '.tpl');
}

There are a couple of things to consider, regarding this code. First of all, we haven’t told Smarty where to find our layouts yet. We can do that by adding a template dir, but this approach means we can’t give our layouts the same name as our templates – Smarty wouldn’t know which one to pick. We could solve this by giving our layouts a different extension, or by setting and resetting our template directory inside our render function, or by using more advanced Smarty functions. For now, we’ll just settle with the constraint that layouts and views can’t have the same name. We can add our layouts directory using the addTemplateDir() function.

function __construct(){
	$this->_smarty = new Smarty();
	
	global $smtemplate_config;
	$this->_smarty->template_dir = $smtemplate_config['template_dir'];
	$this->_smarty->addTemplateDir($smtemplate_config['layouts_dir']);  // <- new line
	$this->_smarty->compile_dir = $smtemplate_config['compile_dir'];
	$this->_smarty->cache_dir = $smtemplate_config['cache_dir'];
	$this->_smarty->configs_dir = $smtemplate_config['configs_dir'];
}

Let’s check it out by changing our index.php file again.

require_once('lib/smtemplate.php');

$tpl = new SMTemplate();
$tpl->render('hello');

It works!

And if we change it to render ‘lipsum’, it works as well:


Step 5: Creating Your Own Modifiers

As the final part of this tutorial, I’ll introduce one of Smarty’s more advanced features, that make it more than a simple templating engine. Smarty contains a number of standard functions and modifiers, but it’s also extremely easy to create your own. Let’s have a look at the modifier we used to format our date:

{$date|date_format:"%d %B"}

If you want a custom modifier, all you need to do is write a PHP function.

This will actually result in a call to the function smarty_modifier_date_format(), with $date and our format string as arguments. This function will return a string, and this string will be displayed. So if you want a custom modifier, all you need to do is write a PHP function. As an example, we’ll write a modifier called ‘weirdcase’, which will uppercase all consonants and lowercase all vowels, i.e. ‘Lorem Ipsum’ becomes ‘LoReM IPSuM’. To do this, create a file called ‘modifier.weirdcase.php’ in the ‘lib/smarty/plugins’ folder. Our modifier will take only one argument, the string that needs to be altered.

/**
 * Smarty weirdcase modifier plugin
 *
 * Type:     modifier
 * Name:     weirdcase
 * Purpose:  turn consonants into uppercase and vowels into lowercase
 * @param string
 * @return string
 */
 
function smarty_modifier_weirdcase($string){

}

We can get our result by defining an array ‘vowels’, turning our string into an array and then traversing it, and checking whether each character is in our vowels array. If it is, we lowercase it, otherwise, we uppercase it. The modified characters are then appended to a result variable.

function smarty_modifier_weirdcase($string){
	$str_array = str_split($string);
	$result = '';
	$vowels = array('a', 'e', 'i', 'o', 'u');
	
	foreach ($str_array as $char){
		if (in_array($vowels, $char)) $result .= strtolower($char);
		else $result .= strtoupper($char);
	}
	
	return $result;
}

This should do the trick, so let’s check it out. Edit the ‘lipsum.tpl’ template and add an h1 containing our weirdcased ‘Lorem Ipsum’ to it.

<h1>{'Lorem Ipsum'|weirdcase}</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean aliquet dignissim diam at vulputate. Aenean nec ligula ac dolor fringilla pharetra. Cras in augue ac tellus dictum pellentesque. Integer elementum tempus lectus, non rutrum sem viverra a. Sed tincidunt sollicitudin dolor, ut blandit magna auctor non. Maecenas sed nibh felis. Donec dictum porta ante at faucibus. Morbi massa tellus, pulvinar id porta id, imperdiet vel nibh. Donec lectus nulla, porttitor a tempor id, cursus vitae leo. Nulla eget nunc eu lorem posuere hendrerit ut ac urna. Aenean sodales lobortis egestas. Integer faucibus hendrerit tempor. </p>

Step 6: Conclusion

Although there is a lot more to Smarty than I could fit within this tutorial, hopefully this should provide you with a basic knowledge of how to work with it. You essentially already know everything you need to know. You should also be able to determine whether you like the idea of using this templating framework or not by now. The more advanced topics, such as filters and blocks, are useful, however, you’ll still do fine without them. You can find documentation on the more advanced features at the Smarty website. Thanks for reading!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://facebook.com/mnowluck mnowluck

    thanks a lot for this..

  • http://www.ao6-labs.eu AoSiX

    Great tutorial, i use smarty at work and it’s pretty cool.

  • Luca

    smarty pretty sucks IMHO

    • http://www.caiapps.com Adam C

      Why?
      IMO, Smarty is great. It makes your templates file much easier to read (i.e., no more in the html) and it also has caching system, which makes your page load faster.

      • http://yeahnah.org Ryan Allen

        PHP itself is a templating language, the fact that you have to wrap your code in tags indicates this.

        By using smarty you give away the ability to do things in straight up PHP, requires you to learn yet another syntax for doing simple things like if statements, and the reason why they have template cache is because Smarty is slow compared to straight up PHP.

        I think it’s an abstraction that is too confusing for beginners, and in practice I don’t see any massive added benefit from using it. A better guideline would be “set up all your variables, get stuff out of the database, figure out access and stuff in one script, then require another php script that is mostly html and makes use of these plain old variables”.

        That way you get the separation of concerns (fetching data, checking access versus putting it all together in HTML), without the overhead of yet-another-library that is slower and doesn’t give you any extra functionality!

        All you need in my opinion is something like PHP ADO and a couple of guidelines like I’ve mentioned above and you can write easy to understand code.

    • http://luciano.longo.me Lucho

      Couldn’t agree more with both of you (Luca and Ryan Allen)

      • http://dagrevis.lv daGrevis

        Imho, Ryan’s right… =P

  • raveren

    A lot of controversy surrounds using a template engine around a templating language (which is what PHP was created to do). Lots of experts advise against it, but the main road to expertise(sp?) is clear code and smarty’s is one of the clearest ones. PHP is tolerable with shorthand, but short tags are a no-no, so my PHP templates border on unreadable no matter how much I try to beautify it (and I usually do, which takes time).

    I’m using smarty3 for my projects now and do it almost exactly as this excellent article suggests (nettuts has risen in quality by the way!).

    • raveren

      The comment system stripped from the
      >PHP is tolerable with shorthand
      sentence.

  • zoran

    Smarty sucks, i agree with Luca, but some projects require you to use Smarty even if you don’t like it. Whatever it is, it’s good to know it, so thank you for the tutorial.

  • http://thadknowsweb.com Thad Bloom

    Thanks,

    I do a lot of work with CS-Cart at work which makes use of Smarty. I sometimes find myself guessing when modifying the code so hopefully going over this thoroughly will help save me some frustration :P

  • Stefan

    I don’t understand the use of this. Smarty just adds another layer of complexity.
    PHP itself was made to included within HTML files, etc.

    You just have to be disciplined enough to strictly divide your business logic and views.

  • http://midnightdesign.ws MidnightLightning

    Using a “Layout” as described here bypasses the Smarty caching system. When I first started using Smarty, I did something similar to this (using a “main.tpl” layout file that used {include $content} to render the page; no custom class needed). Problem with this method of including the content from another template is if Smarty caching is used, every site uses the one layout template, so all gets cached as the same page, creating an illusion that all pages of the site look the same. A better solution that I work with now is to have a “header.tpl” and “footer.tpl” file that are {include}d in every content template. That way the content template gets cached, not the layout template.

    And, any reason you went off and made your own class object, rather than extending the Smarty class object with your added functionality?

  • Joe S

    I’ve been wanting to learn how to use Smarty more as I’ve had a couple projects that needed it. It would be nice if this could be a series. :D

  • Djinn

    Oh great! thanks … can you do more tutorials about smarty? i’m really interested in this. Thank you

  • Ryan

    Is this suppose to be a CMS or something?

  • DJ

    You know, as long as we are ‘just trying it out’ before we decide whether to like it or not, as well written as this is, it would make a great screencast so we could actually see it work from someone who had already gone to the trouble of downloading and installing it before we decided whether or not to invest in the effort and band-width. There are some things better seen than explained, this may be one of them. How about making this a screencast?

  • Luke

    I have tried to use smarty before but couldn’t get my head around it. It seems kind of pointless to me. I never bothered to dig much into it though because it didn’t seem like it was even worth using. If I was creating an app I planned on redistributing I might use it but for my own projects I don’t need to add this overhead.

  • http://adeelejaz.com/ Adeel Ejaz

    Great tutorial but I’ve moved on from Smarty last year. It was mainly because of the braces and javascript. Now I use twig template engine and haven’t looked back since. Its definitely worth a try. Miles ahead of Smarty :)

  • http://mixmo-anime.blogspot.com kankuro

    It doesn’t matter if you use that framework template or not…. as long as you feel comfortable for it, then go and if not then don’t use it…. find a way that you feel comfortable on using those various apps.

    nettuts provide us a great tutorial, if we like it or not…. long live nettuts…. the best.

  • SAPONO

    waiting the part 2 of this introduction……

  • http://vijaypadhariya.blogspot.com Vijay Padhariya

    Dude.

    Really interesting Article though, I was using Smarty before a year ago, but i avoid using it, as it costs Slowing down my site a little bit, some of my clients told me that it causes this problem so i refused to use it.

    you see as we use this engine, php’s process become double.

    1. its parses HTML data into PHP
    2. again PHP parser parses PHP Template into HTML to give HTML view to client side.

    so its good not to use, better use inbuilt templating serviced provided by good frameworks like codeignator, symfony, magento etc etc.

    Thanks,
    Vijay Padhariya

  • http://www.dailygrind.it Sergio

    Is this project still alive?

    • http://www.pitgroup.nl Frank

      haha :)

      i stopped using smarty when they started supporting chained method calling from objects

  • http://www.codeforest.net/ Codeforest

    I think that learning yet another syntax is a little bit overkill. You can achieve the same thing with plain PHP.

    But still, I like this tutorial as it gives me an inside look to Smarty without me having to learn it.

  • http://www.wa-co.be Waldo

    I can agree with the posts that Smarty is not really necessary just for the template-thing, but Smarty gives more then just seperating your PHP-code from your HTML.
    I think that the caching-solution is also a good add-on for your project. I haven’t worked with another caching solution but Smarty, so maybe there are other solutions for that, but template + caching makes it a nice addon for my PHP-projects..

  • http://forbs1994.deviantart.com/ Forbs

    Great tutorial,thanks!

  • http://thedevelopertuts.com Bratu Sebastian

    Smarty is complicated, but you might need it in a certain project. I had to learn it before, when I had a client with an existing store.

    It was awful. But I get the point with Smarty. It’s just not my thing, because I write my own {tag} parser or use CodeIgniter’s, which is great!

  • http://vestimir.com vestimir

    IMO Smarty is great for teaching you how to separate the html from the php, I used it for almost 5 years, and now when I have this culture of separation I am back to PHP templates and I am happy. With simple one file class, that does not use regex parsing for the templates, everything gets instant faster.

  • http://www.twitter.com/mamunabms Abdullah Al Mamun

    Very Basic ignoring some factors like caching.
    I hope some follow-up tutorials is coming next.
    Thanks. :-)

  • Ben McRae

    I used Smarty2 commercially for almost 2 years and it proved very successful. I wouldnt worry about the time a smarty template takes to compile when you have issues with DB access/queries to worry about.

    Im looking forward to see whats changed in version 3! Im sure this will be a great tutorial :)

  • http://www.buitenaardig.nl/ Philip Wallage

    MODx satisfies all my needs! Smarty has always been on my to-do list but I just havent found any motivation to kick-start it.

  • http://www.crearedesign.co.uk Steve Maggs

    From my limited exposure to Smarty it seemed the biggest problem for a commercial website was caching, which caused lots of problems and meant that to push through changes made using the company’s CMS the Smarty cache had to be manually cleared frequently.

    As a templating engine it’s one of the clearest but I’m with the others here who try to avoid adding that extra un-necessary layer of code whenever possible.

  • went_to_france

    ‘global’? really? why not pass that config array into the constructor?

  • Dave k

    Was happy to see this, I’ve wanted to look in to smarty for a while. Be good to see a follow up tutorial

  • http://www.avozdoevangelho.com.br Nilson

    Great.

    I would like to learn more about Cache.

  • http://www.jsxtech.com Jaspal Singh

    Excellent tutorial for beginners.
    Thanks for sharing.

  • http://itvillage.site11.com/ IT Village

    I am big fan of nettuts+. great post. can I share it on my new website?

  • http://www.salebab.net Aleksandar Babic

    Smarty is good and have some nice features like caching. It is not difficult to learn.

    But I don’t see any advantage to create and use SMTemplate class on this way. If you ever want to migrate to some other template system, you will have other, much greater problems.

  • Steve

    Never hurts to learn something new, but I would never put all your eggs into the “Smarty” basket. Before the advent of great PHP frameworks it had it’s uses, but now…

    Go with any framework and write some real MVC code :P

  • exped

    Forget about Smarty. It has so many annoying “features”: no method chaining, JS/CSS unfriendly, slow, poor API).
    Just switch to Twig Template Engine. Far more better. Supports template inheritance (page layout belongs to view layer, not controller), is JS/CSS friendly, relatively fast (comparing to raw PHP), easy to extend.

  • http://twitter.com/korenbr Koren Berman

    Good intro. More people should definitely be using templating frameworks like Smarty. I was underwhelmed by WP 3.0 when I learned that they had still not implemented anything like that for the templates. Tumblr and EE do it, why does WP lag behind on this? not sure.

    • Springmann

      You can do it by yourself, using any template framework you want (including Smarty). Anyway, the way that WP works is awesome and much more interesting and flexible than Drupal or Joomla, for example.

  • http://artflutter.com Alex

    I’ve used Smarty v2 in the past but much prefer Dwoo which is built for php5, similar syntax / functionality just faster. Smarty v3 looks a bit more promising but I wouldn’t be using it for a commercial project just yet.

    • http://cristianwil.com.ar Cristian

      Same here, Dwoo really rocks!!

  • http://douse.web.id waro

    I use Smarty since 2007 and my designer loves it.
    Smarty also has good forum and very helpful members.

  • Arun

    We use PHPTAL, its way easier than smarty and gets jo done. Perfect for webdesigners like me, who already are profficient in HTML, but dont know PHP.

    • kemy

      agree

  • http://superdit.com aditia

    owh now I see there are still a lot smarty users, cause since I knowing php framework I rarely using smarty

  • Bargok

    Smarty is great..and this tutorial doesn’t show why..shame.
    I don’t like the wrapper, and things such as globals really make me a sad panda.

  • martin

    smarty is great, I use it mostly for developing typo3 extensions.

  • http://www.frutesca.com Mack

    To me, template engines arise to the occasion when you have to encode a piece of software, but still allow the customer some form of customization. That is the only time I found smarty useful.

  • nosmartyplease

    I will use Smarty templating when hell freezes over. Smarty is the enemy of scaling and performance websites.

    • Ionut

      I will not agree with that, my company uses Smarty for really big content websites, over 150k unique visitor/day and is working awesome.

  • thomasw

    The author forgot one important thing: escape your HTML output (modifier “escape”). Or you will die with XSS ;-)

    I use smarty to create HTML and PDF documents – yes, PDF, with my own meta language processor! A good way to separate PDF document formatting from code.

    To everyone who thinks smarty is a performance killer: Your “compiled” template will be just executed (included) PHP code – nothing else.

    Also I think the following code is easier to maintain:

    {$blah|escape}

    or

    You can create your own modifiers, e.g. for escaping to UTF-8. With your own functions and modifiers you can also easily create a “higher” level of HTML / web application design.

    • thomasw

      OK, now with correct escaping for the samples ;-):

      <strong>{$blah|escape}</strong>

      or

      <strong><?php echo htmlentities($blah); ?></strong>

    • Valerij Primachenko

      Compiling of the templates is a nice feature, but i don’t think it’s just as fast as hand written (and hand optimized) code. Its like compiled C++ (please c++ programmer don’t hit me for this comparison) code against pure Assembler for desktop applications.

  • gabi

    hi. i get: Fatal error: Call to undefined method Smarty::addTemplateDir() in /home/www/smarty_example/lib/smtemplate.php on line 18. i searched on the smarty deocumentation and i didn’t found this method

    • Linh

      You must get Smarty version 3.0xx to use that method.

  • http://www.adamjleonard.com Adam Leonard

    Smarty is not something I suggest learning. It only adds a layer of complexity, it doesn’t solve anything. If you are looking for any sort of templating checking out HAML, it’s beautiful.

  • mdennisa

    this is a nice tutorial, but…
    I prefer to use codeigniter.

    and I have no idea why some peoples still use smarty template for codeigniter –”

  • http://www.satya-weblog.com/blogroll Satya Prakash

    For another smarty template tutorial you can visit the post – http://www.satya-weblog.com/2007/04/php-template-smarty-template.html

  • pixibug

    I use smarty 2 years, and this template engine integrates seamlessly with a MVC architecture (no slow down, cache system, easy to create your own plugins and modifier). And most importantly, when you work with a team of html graphic designer (creating view), smarty is easily accessible and the code is more clear than php IMO.
    Good tutorial.