Sunday, October 15, 2006

A Smart move - The Smarty template Engine

As was discussed in the previous blog, our classified advertising site is coded using PHP.

If you have looked at more than a few php scripts, then you will know that
the combination of the php code embedded thorough the HTML code all in the one script is
both messy and cumbersome,
quite honestly it looks a mess.
For larger projects, such as this one, the coding would put anyone off the subect
for life.
There is a much better way.

Using a template Class allows us to fully seperate the php code from the HTML.
Using such a class is almost essential for these larger projects.

Whilst Smarty is not the only templating class available, it is one of the
best. It has been around for some time, so it is mature and stable. Also it is public domain.


The Smarty class
allows you to code all of the php in one script and place all of the
HTML code in a seperate file. This HTML file is not quite free of
programming, but it is simplified to the extent that it is merely
referencing of variables , looping of arrays and using simple if
statements.

All of the complex stuff, like referencing of
databases, parsing of xml data figuring out sessions etc etc is done by
clean, clear, simple, pure php code.


The smarty HTML files are called templates(no surprise there) and use the extension .tpl
They have embedded within them the much simplified smarty programming code.


The PHP code gets the required information, puts it in variables or arrays and passes these to Smarty. via a statement like:-

$Smarty->assign('description',$description);

You
them tell Smarty which template(s) to use and the class will processes
these templates with the embedded code to produce the final HTML Page.

such as:-

$Smarty->display('header.tpl');
$Smarty->display('body.tpl');
$display->display('footer.tpl');


There is a lot more to Smarty than mentioned here. Suffice to say, that we will cover the subject more thoroughly as and when we need it throughout this blog.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home