• Feed RSS
Showing posts with label Template Engine. Show all posts
Showing posts with label Template Engine. Show all posts

Quick Tip: Working with the Official jQuery Templating Plugin

Quick Tip: Working with the Official jQuery Templating Plugin: "
Just this week, the jQuery team announced that Microsoft’s templating plugin (along with a couple others) is now being officially supported. What this means is that the plugin will now be maintained and updated directly by the core team. In this video tutorial, we’ll review the essentials of the plugin, and why it’s so awesome.





As a quick example, we’ll, again, refer to the Twitter search API example from Friday (think Bieber). The only difference is that, this time, we’ll use an HTML template to attach the returned data, rather than muddying up our JavaScript!

Months ago, Andrew Burgess introduced you to this plugin, still in beta. However, today, we’ll integrate the plugin into real-live code.




Crash Course




Step 1 : Import jQuery and the Templating Plugin


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="jquery.tmpl.js"></script>



Step 2 : Create your Template


<script id="tweets" type="text/x-jquery-tmpl">
<li>
<img src="${imgSource}" alt="${username}" />
<h2> ${username} </h2>
<p> ${tweet} </p>
{{if geo}}
<span> ${geo} </span>
{{/if}}
</li>
</script>

  • Notice how this template is wrapped within script tags, and that a type of text/x-jquery-tmpl has been applied.
  • We reference template variables names by prepending a dollar sign, and wrapping the property name within curly braces.
  • If statements can be created by using two sets of curly braces, as demonstrated above. (See screencast for more detail.)




Step 3 : Find Some Data to Render!


In this case, we'll do a quick search of the Twitter search API.

<script>

$.ajax({
type : 'GET',
dataType : 'jsonp',
url : 'http://search.twitter.com/search.json?q=nettuts',

success : function(tweets) {
var twitter = $.map(tweets.results, function(obj, index) {
return {
username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo
};
});
}
});

</script>

Thanks to Peter Galiba (see comments), for recommending the more elegant $.map solution, shown above.

Refer to the screencast for a full walk-through of the code above. Most importantly, though, is that we're creating an array of objects. This will then serve as the data for the the template that we created in step two. Notice how the property names:

username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo

...correspond to the template variables that we created in step two.



Step 4 : Where Should the Mark-up Be Rendered?


Next, we must designate where the mark-up and data should be rendered. We'll create an unordered list for this purpose.

<ul id="tweets"> </ul>



Step 5 : Render the Data


Finally, we attach the data to the template, and append it to the unordered list (#tweets) that we created in step four.

$('#tweets').tmpl(twitter).appendTo('#twitter');

  1. Find the script (template) element with an id of tweets.
  2. Attach the twitter array to this template.
  3. Add the new mark-up to the DOM.



Final Source


<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="style.css" />

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="jquery.tmpl.js"></script>
</head>
<body>

<h1> Tweets about Nettuts+ </h1>

<script id="tweets" type="text/x-jquery-tmpl">
<li>
<img src="${imgSource}" alt="${userName}" />
<h2> ${username} </h2>
<p> ${tweet} </p>

{{if geo}}
<span>
${geo}
</span>
{{/if}}
</li>
</script>

<ul id="twitter"></ul>

<script>
$.ajax({
type : 'GET',
dataType : 'jsonp',
url : 'http://search.twitter.com/search.json?q=nettuts',

success : function(tweets) {
var twitter = $.map(tweets.results, function(obj, index) {
return {
username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo
};
});

$('#tweets').tmpl(twitter).appendTo('#twitter');
}
});

</script>
</body>
</html>



So What do you Think?


Now that the templating plugin is officially supported by the core jQuery team, will you be using it in your future projects?
"
read more

Introduction to the Smarty Templating Framework

Introduction to the Smarty Templating Framework: "
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!
"
read more

Building HTML in jQuery and JavaScript

Building HTML in jQuery and JavaScript: "
It can be a pain to create HTML elements in JavaScript. In this article I will outline a few ways I deal with HTML. First, we’ll look at whether to use an HTML string or a jQuery object, then look at my little HTML string builder utility and finally get some links to templating libraries for building more complex HTML.

HTML String, or jQuery Object?


The first question you have to ask yourself is whether or not it makes sense to build out HTML as jQuery objects, or if you require the speed of building strings. In jQuery 1.4 you can built HTML objects that have events attached. Consider the following code.


$("input", {
id: "permissionsInput",
name: "permissions",
type: "checkbox",
click: function(){
update();
},
checked: "checked"
}).appendTo("#myForm");


You can see here that not only can you build out HTML with attributes, but you can attach events (like click) too. This ability was added to jQuery in version 1.4.

If you were doing this 100 times though, it might be very slow. The better way to do it would be to build out the HTML strings first, and then attach events later with jQuery’s live or delegate methods.

Building HTML Strings


So now you want to build an HTML string because you have a lot of elements to build and you can attach events later. There are basically two ways to do this. You can build one long HTML string and append it:


var data = ["a", "bunch", "of", "things", "to", "insert"];
var html = '';
for (var i=0; i < data.length; i++) {
html += "<td>" + data + "</td>";
}
$("#tablerow").append(html);


Or you can use an array which is typically a little faster.


var data = ["a", "bunch", "of", "things", "to", "insert"];
var html = [];
for (var i=0; i < data.length; i++) {
html[html.length] = "<td>" + data + "</td>";
}
$("#tablerow").append(html);


Building Complex HTML Elements


When you are building more complex HTML, things get a little hairy in the code. Take our previous example with jQuery and turn it into raw HTML building:


html = '<input id="permissionsInput" name="permissions" type="checkbox" checked="checked">';


Not bad, but what if those attributes were set programmatically? This is typical.


html = '<input "' + inputId + '" name="' + inputName + '" type="' + inputType + '"' + (isChecked ? 'checked="checked"' : '') + '/>';


Yuck! So to solve this I wrote a little ditty function called buildHTML. The code isn’t perfect and it could be written better (please do) but it looks like this:


// my little html string builder
buildHTML = function(tag, html, attrs) {
// you can skip html param
if (typeof(html) != 'string') {
attrs = html;
html = null;
}
var h = '<' + tag;
for (attr in attrs) {
if(attrs[attr] === false) continue;
h += ' ' + attr + '="' + attrs[attr] + '"';
}
return h += html ? ">" + html + "</" + tag + ">" : "/>";
}


So now our code for building that same input becomes:


html = buildHTML("input", {
id: inputId,
name: inputName
type: inputType
checked: isChecked
});


Nicer, huh? Get the gist for buildHTML and examples. And by all means fork it and make it better.

Templating


Another way to build out more complex HTML is using templating. John Resig has a great article and some code examples for JavaScript Micro Templating

There is a templating language called mustache that I see a lot of people using. Also, there has been some proposals for templating being built into jQuery’s core, however for now there is a jQuery plugin on github jquery-tmpl. Rey Bango wrote an article explaining using jQuery templating.

If you have any other HTML building tips, please share!
"
read more

Template Engine: An Overview of Smarty Templates & Other Comparisons

Template Engine: An Overview of Smarty Templates & Other Comparisons: "
The template engine's job is to help separate out application model logic from display logic and to provide a simpler, more readable way to add functionality to your display files. Since HTML was never meant to handle arbitrary logic, it is generally kept separate from the Model and Controller layers of an application - learn more about MVC.

Template Engine: An Overview of Smarty Templates & Other Comparisons



However, it's inevitable that at least some presentation logic gets mixed up into the HTML template file due to requirements such as 'Alternate background color of each table row' or 'Show only positive balances'. So, rather than mix standard PHP code into the HTML template file, template enginhowes were conceived which mask common PHP functions and tasks with more presentable and concise code and allow for a deeper separation of logic and markup.

Standard HTML Template vs Template Code


So while a standard HTML template might contain code like this:

<?php foreach ($items as $item): ?>
<div><?php echo $item; ?></div>
<?php endforeach; ?>

Template code might look more like this:

{foreach from=$myArray item=foo}
<div>{$foo}</div>
{/foreach}

As you can see, the latter would be much more readable by non-coders and looks more like typical markup than PHP code. But although the code may be prettier, one of the criticisms for using a template engine is the extra resources and time spent compiling the template code into actual PHP code. This really is a give and take. If you are a sole developer working on a project and you don't really foresee having more than a few developers working on the project at a time, then maybe a template engine isn't for you. On the flip side, if you end up having multiple developers and front end coders editing your code later on, a template engine could be a huge benefit.

While there are many template engines out there, some stand out among the others. Smarty Template Engine is one of the older engines that has been scrutinized and improved upon year after year. Because of its age, there is a wealth of resources for solving Smarty problems across the net.

Smarty vs Other PHP Template Engines


Smarty describes itself as a Template/Presentation Framework. Its goal is to not to be a simple tag-replacing engine, but a full-featured template engine that allows for simpler, more painless development without sacrificing speed, security or performance. So, does Smarty live up to its definition? Well, let's see how it stacks up against the other template engines out there. Here is a quick comparison with a few of other popular PHP template engines.

Smarty Template

PHPTAL


One thing I have always noticed about Smarty is that it is usually pretty easy to find answers to you question with a quick Google search or a search in the Smarty forums. PHPTAL doesn't seem to have quite the wealth of information enjoyed by Smarty users, but I guess that comes with popularity. What PHPTAL does well, however, is template syntax. It just seems a little bit more logical and readable than Smarty.

PHPTAL

Here's a simple foreach statement in Smarty and PHPTAL.

Foreach in Smarty:

{foreach from=$myArray item=foo}
<div>{$foo}</div>
{/foreach}

Foreach in PHPTAL

<div tal:repeat="item items" tal:content="item">
this is just example content and is not required, kind of
like a comment. Neat!
</div>

There are tons of really cool features available in PHPTAL that make it a fairly strong template engine but Smarty definitely seems a bit more beginner friendly, though not quite as powerful as PHPTAL.

Dwoo


Dwoo is a template engine created in 2008 in direct opposition to Smarty. Smarty still supports PHP4 and doesn't take advantage of some of the object-oriented features of PHP5, so Dwoo was created as a modern alternative to Smarty. Since Dwoo is not nearly as old as Smarty, there are naturally a lot more resources on the internet for help with Smarty templates. However, Dwoo, being a more modern engine, is focused on speed and utilizes template inheritance as a main feature. The syntax for the two engines is similar, which makes sense since Dwoo was created as a direct alternative to Smarty.

Dwoo

Foreach in Smarty

{foreach from=$myArray item=foo}
<div>{$foo}</div>
{/foreach}

Foreach in Dwoo

{foreach $arr val}
<div>{$val}</div>
{/foreach}

Savant


Savant describes itself as The simple, elegant, and powerful alternative to Smarty and takes a much simpler approach to templating. Savant doesn't utilize its own pseudo-language for its template files but rather relies on standard PHP code. Because of this, there is no caching for compiled PHP scripts like Smarty and no pre-filtering or post-filtering is required since all templates are written in standard PHP code. This means that Smarty's code (as well as many other template engines that utilize pseudo-code) is shorter overall.

Savant

Foreach in Smarty

{foreach from=$myArray item=foo}
<div>{$foo}</div>
{/foreach}

Foreach in Savant

<?php foreach ($myArray as $foo): ?>
<?php echo "<div>$foo</div>" ?>
<?php endforeach; ?>

So what is the point of using a Template system like Savant? To separate your application model logic from your display template logic. It's as simple as that. Is it better than a template engine that uses a pseudo-language like Smarty? That's really up to you to decide!

Rain TPL


Rain TPL is a fairly lightweight template engine that was released back in 2007. While it doesn't seem to be as feature heavy as Smarty, it does use a fairly similar syntax that will make Smarty users feel right at home.

The Rain TPL website has decent documentation but there doesn't seem to be an active forum for the software. This is a huge disadvantage when it comes to troubleshooting. It seems that if you are working on a fairly simple project then Rain TPL could be a decent solution but if you are looking for a template with a more refined and feature heavy pseudo-language with community support, Smarty is the way to go.

RainTPL

Foreach in Smarty

{foreach from=$myArray item=foo}
<div>{$foo}</div>
{/foreach}

Foreach in Rain TPL

{loop name=”myArray”}
<div>{$value}</div>
{/loop}

Overall, what Smarty lacks in speed or features, it makes up for in resources and ease of use. I have yet to run into a problem in Smarty that couldn't be sorted out by using a few caffeine-powered keywords in a Google search or by checking out the Smarty forums.

Setting Up Smarty Templates for Your PHP Project


Here is a step by step guide that will get your PHP project up and running with Smarty Templates in minutes.

  1. Head over to Smarty Download page and grab the latest stable release.
  2. Create /smarty within your root directory of your project, in my case c:/wamp/www/projectname.
  3. Unpack the contents of /libs from the Smarty pack you just downloaded into /projectname/smarty/libs.
  4. Create the following directories inside of /projectname/smarty

    • templates
    • templates_c
    • cache
    • configs


That's it! Now let's initialize Smarty and get it setup. Paste the following code into index.php file in /projectname.

<?php
// importing the Smarty class
require_once('smarty/libs/Smarty.class.php');

// now make an object of the class
$smarty = new Smarty();

// mapping smarty directories
$smarty->template_dir = 'smarty/templates';
$smarty->compile_dir  = 'smarty/templates_c';
$smarty->cache_dir    = 'smarty/cache';
$smarty->config_dir   = 'smarty/configs';

// assigning values to variables and displaying using template
$smarty->assign('greeting', 'Hello');
$smarty->display('index.tpl');
?>

Now let's create our first template file. Within /smarty/templates create index.tpl and paste in the following code.

<html>
<head>
<title>First Smarty Template</title>
</head>
<body>
<p>{$greeting}!</p>
</body>
</html>

If you see 'Hello!' outputted on the screen then Smarty has been setup successfully.

In our example we put our templates folder inside the smarty directory but remember you can assign that to whatever you'd like by assigning the directory path to $obj->template_dir. The same goes for cache and config directories.

How Is Smarty Going to Help You?


Smarty mayhave be a bit of a learning curve at the beginning but the more you work at it, the faster you will develop your front-end. Most of the basic Smarty functions, such as assigning variables, if else, foreach, counters, etc. can be found by searching the Smarty manual. The Smarty forums are also a great resource. Chances are there is someone there who has had the same problem you are having.

Within a few days you should start noticing the organizational benefit and hopefully an increase in your development time. You may also find an even greater advantage to Smarty when working within a team. Since some team members have front-end developers who aren't familiar with PHP or syntax, it is usually much easier for them to work within a Smarty template than a standard HTML file with PHP code integrated. Smarty is made to be more readable and concise, leaving less room for error.

Resources to Help You Become a Smarty Pro



While Smarty may have its short comings, the wealth of community and support rallied behind this project more than makes up for them. This is a refined and easy to use template system that gets better and better with each release. It has been around for years and doesn't seem to be going anywhere. Let us know what you think about Smarty Template in the comment section below.



Written by: Eric Bieller for Onextrapixel - Showcasing Web Treats Without A Hitch | 13 comments
"
read more