views:

1588

answers:

19

Why should I use templating system in PHP?

The reasoning behind my question is: PHP itself is feature rich templating system, why should I install another template engine?

The only two pros I found so far are:

  1. A bit cleaner syntax (sometimes)
  2. Template engine is not usually powerful enough to implement business logic so it forces you to separate concerns. Templating with PHP can lure you to walk around the templating principles and start writing code soup again.

... and both are quite negligile when compared to cons.

Small example:

PHP

<h1><?=$title?></h1>
<ul>
  <?php foreach ($items as $item) {?>
  <li><?=$item?></li>
  <?php } ?>
</ul>

Smarty

<h1>{$title}</h1>
<ul>
  {foreach item=item from=$items}
  <li>{$item}</li>
  {/foreach}
</ul>

I really don't see any difference at all.

+1  A: 

Mostly I think to avoid any "unsafe" backend logic to be applied in templates. Since most of the times templates are handed to designers, we only want to give them a closed set of things they can do.

Luca Matteis
Ok, so this would be point 2 in my pros. You can always (at least in Smarty) inject templating engine with unsafe things. It is only a bit harder :-)
Josef Sábl
Then don't use Smarty :)
Luca Matteis
+17  A: 

Yes, as you said, if you don't force yourself to use a templating engine inside PHP ( the templating engine ) it becomes easy to slip and stop separating concerns.

However, the same people who have problems separating concerns end up generating HTML and feeding it to smarty, or executing PHP code in Smarty, so Smarty's hardly solving your concern separation problem.

See also:

Kent Fredric
Yes, this exactly is the case of problem we have with Smarty. Feeding html code to smarty variables and using {php}{/php} tags.
Josef Sábl
This is something I've thought about a bit aswell. Can you give some examples of the things you might do in a 'view' (MVC context) in pure PHP? eg. text trimming, capitalisation, loops. Where is the line drawn for other 'concerns'.
sanchothefat
@sanchothefat: I have the opinion of template languages that they all suck and don't entirely seperate ever in any implementation, you just have to draw your own line on a project-by-project basis. I'm working on having *no* code in my template, but thats a way off.
Kent Fredric
Display logic is always a slippery slope. At what point does zebra striping or text formatting become "real" logic? My opinion is that if you're asking yourself this question at all and not just saying, "aw screw it" you are on the right path.
Nick
@sanchothefat: Someone pointed out that you should never change any value inside the template. This is very reasonable minimum. I personally would go further, limiting PHP to only simple functionality. Not many chained commands.
Josef Sábl
Excellent answer. Templating systems are one of those things where you haven't paid your dues yet if you haven't written one yourself, only to throw it away later. It really boils down to what can you do *consistently* that's maintainable by those you work with ... and yourself.
dreftymac
This is the maintainable code you will be writing with smarty... seriously... I checked blame and something like it was written last week...::: {foreach from=$array|@array_keys item='key' }{foreach from=$array|@array_values item='value'}{if $smarty.post.var==$key}{$value|escape:'html'}{else}{$key|escape:'html'}{/if}{/foreach}{/foreach}
SeanJA
+1  A: 

Your analysis is reasonable. I suppose:

  • Template designers and back-end programmers may not be one in the same, so it promotes separation.
  • It protects you from yourself somewhat in that you can't really do "too much" PHP in your templates.
  • It may be easier to optimise/precompile templates in some scenarios? (This is speculation)

Personally, I think they're more hassle than they're worth. Particularly they don't work if you want to hand the templates to "designers" since the WYSIWYG tools don't know what to do with them.

Draemon
+6  A: 

The main reason people use template systems is to separate logic from presentation. There are several benefits that come from that.

Firstly, you can hand off a template to a web designer who can move things around as they see fit, without them having to worry about keeping the flow of the code. They don't need to understand PHP, just to know to leave the special tags alone. They may have to learn a few simple semantics for a few tags but that is a lot simpler than learning the whole language.

Also, by splitting the page into separate files, both programmer and designer can work on the same 'page' at once, checking in to source control as they need, without conflicts. Designers can test their template visuals against a stable version of the code while the programmer is making other, potentially breaking changes, against their own copy. But if these people were both editing the same file and had to merge in different changes, you can encounter problems.

It also enforces good programming practice in keeping business logic away from presentation logic. If you put your business logic mixed in with the presentation then you have a more difficult time extracting it if you need to present it differently later. Different modes of presentation in web apps are increasingly popular these days: RSS/ATOM feeds, JSON or AJAX responses, WML for handheld devices, etc. With a template system these can often be done entirely with a template and no or little change to anything else.

Not everybody will need or appreciate these benefits however. PHP's advantage over Java/Python/Ruby/etc is that you can quickly hack up web pages with some logic in them, and that's all well and good.

Kylotan
Excellent answer. The separation of logic and presentation is the biggest benefit. Allowing the design to change without worrying about the code increases productivity substantially.
William Brendel
This is all true, of course, but you don't need separate template engine to do that. PHP itself can be used the way you describe. Maybe it is my bad wording. I mean templating system as product not as approach.
Josef Sábl
The benefits of using 'off the shelf' software are the same here as anywhere else: you gain the benefits of prior testing by the community, ready documentation, and almost free maintenance going forward.
Kylotan
+1  A: 

I like the ability to trivially display any template from any PHP file (and include fragments of templates inside each other, for common elements like nav bars). For example, suppose you had a page that normally prints some information if you're logged in or an error if you're not. With PHP, you'd write something like:

if (loggedIn)
{
    // print lots of HTML here
}
else
{
    // print error message
}

In Smarty, it could be something like this (forgive my probably wrong syntax, it's been a while):

if (loggedIn)
{
    $smarty->bind("info", someObject);
    $smarty->display("info.template");
}
else
    $smarty->display("error.template");

If you were really clever, you could even display the login page template instead of the error template, optionally with a message explaining why the user ended up there. And if you went with the technique as I wrote it and then decided you wanted to switch to displaying the login box, it's only a single line change! For me, it's not just about keeping the separation of view and logic, but about the ability to reuse common elements of the view from many places.

rmeador
its "assign", but thats mostly right.
Kent Fredric
This can also be done in PHP with include, but I guess that Smarty can do this more easily.
Josef Sábl
+2  A: 

I'm happy using an MVC framework like code igniter. I find that in the 'views' I tend to stick to php code that relates only to how values are displayed. I have a library of formatting functions i can use in the views to that effect. One of the premises of code igniter is to avoid a templating language because of the way it can restrict you and the slow down incurred.

I find that is better for designers to learn some PHP, so that they can achieve what they need to do eg. alternating class names. It will also make them more useful in the long term and it's not a huge leap from one syntax to the other.

sanchothefat
+1  A: 

I don't think you should use a template engine. Instead you should use something like Zend_View which encourages you to do separate logic from presentation, but allows you to build your presentation layer in PHP.

Zoredache
Zend_View its a template engine
Gabriel Sosa
I am now starting new project with Zend Framework, and it is like, wow, how could I do that without that before? :-)
Josef Sábl
A: 

I'd wager that if a PHP template language was so coercive as to force you to use it, you wouldn't use it at all. The ability to 'jump out' and do things your way when in trouble is one of the attractives of PHP.

I don't say that it's a good thing, nor that the code will be maintainable, just that in the initial considerations, I wouldn't choose a template language that blocked me completely.

Otherwise, I agree that templating systems help you divide work between coding and design, and possibly letting designers design and the coding to us.

Adriano Varoli Piazza
+1  A: 

One template engine advantage that I didn't see was the possibility of dynamic html elements - something like asp.net controls. For example, with PEAR's HTML Template Flexy you can have dynamic form elements that automatically maintain state. A regular html select element can be populated and have the selected item set in the code behind without loops or conditionals in the template.

rick
+1  A: 

I think that cleaner syntax is quite a big win. Although it may look like only a few characters, but when you do it every day, then each character starts to count.

And {$myvar|escape} is IMHO quite a bit shorter than <?php echo htmlspecialchars($myvar); ?>. (Keeping in mind that <?=$foo?> syntax is only available when it is specially enabled in PHP conf.)

Rene Saarsoo
Ok, but everytime I want to write something in Smarty, I reach for Smarty cheat sheet, thus not saving much of time :-)
Josef Sábl
@JS once you start using it every day you dont need to see the sheet
Gabriel Sosa
I still need the cheat sheet after a year of using it because I run into ridiculous cases where it is [] instead of . Make up your mind smarty! Which is it?!?
SeanJA
+3  A: 

PHP is pretty much a templating system. The key is to force yourself to separate logic from presentation on your own. Using Smarty or something like that only makes it slightly more inconvenient to mix logic and presentation. If you can't make yourself separate them on your own, using a templating system isn't going to help. All it's going to do is eat up additional processing power.

The key is to not alter any values in your presentation code. To do this, I think PHP itself is just as effective as Smarty if you use the if/endif syntax:

<?php if($some_test): ?>
   <em>Some text!</em>
<?php endif; ?>
Wickethewok
+1  A: 
  • You want to use a file with PHP code as a template? Fine.
  • You want to use your variables in said template? Fine.

Just remember to separate logic and final output (presentation). This is better accomplished with a templating framework. But you dont have to learn something like Smarty.

  • If you use Zend_View or similar you can use PHP code all the way.

Many people here have the correct reply. Smarty is not templating in PHP. Far from it. Smarty is there mostly for those who have to use designers (ie non-programmers) to edit and setup the display of pages. If everyone who are gonna change the layout of your pages can program, you can go with a more PHP code oriented templating system. But you really should have all your output data ready and send it to the template. If you let each page fetch, process and display the content, you will have to refactor it sooner then later.

OIS
+1  A: 

When you're writing code for someone else. For example, I was once involved in the creation of a rigid web application framework that should be customizable for our customers. One important request was that the customer could hire a designer to modify the templates without having to be able to program. Even more important, he might not be authorized to change the code.

Smarty for example allows to implement quite rigid restrictions on what the template may do. Basically, our application disabled all but the most basic code constructs and a selected set of modifier functions. So we had two goals that were served well by a template engine: simplicity and security.

Konrad Rudolph
+2  A: 

Using non-PHP templates with the excuse of separating logic is nonsense. If the developer doesn't understand what the business-view logic separation is and how it should be done, then the problem must be addressed appropriately. Otherwise you end up with HTML in business logic or business logic in templates -- no templating engine is going to save you. You have to teach the developer the basics.

And if the developer does understand that, the templating system is only a limitation. It doesn't add any value to the development process, only overhead of learning a new syntax, keeping another library up to date, and slower execution. While the latter can be solved with caching and whatnot, this only remedies a problem that otherwise wouldn't exist. So, templating systems offer no value, no advantage at all.

There is one exception, though, where I think using a non-PHP templating system is reasonable: when view-logic programmers must have limited access to the templates. For example if you're a provider for a blog-hosting system and you want to allow your users to personalize and code their templates, without allowing them to execute arbitrary code. This argument, however, does not apply to cases where a designer is willing to learn a little code to help programming the UI. If he can learn Smarty, he can surely learn PHP.

gasper_k
+1  A: 

You forgot htmlspecialchars() twice. That's why you need templating system.

Smarty is poor. Don't judge templating systems based on that.

porneL
+4  A: 

for me, one of the big features of templates engines is that the cache layer its transparent for you. I've been using smarty long time ago, and the cache stuff make the life easier. also the smarty design allow you to use your own cache function. In my case I choose if for some page should use memcache or disk to store the template output.

in the other hand if your site has a big traffic and you dont know how to manage smarty and tuning it well this any template engine could be a site killer. but even not using smarty your site can die also.

flickr is currently using smarty. its shouldn't be soo bad, isn't?

Gabriel Sosa
+1 for what I was gonna say.
GloryFish
+1  A: 

And let us not forget the future. Websites are old almost the minute they are published. You WILL need to update the look and feel at some point. If you maintain separation often times a designer alone can complete a whole new website with the same programming on the back end. This allows for faster and cheaper redesigns, allowing you to only involve the programmer if new functionality is required.

UberDragon
but the designer could do that without smarty but with php too. just some words:P a foreach or an echo, right?
weng
+4  A: 

There is still a good reason for a template system to use, however not Smarty, but PHPTAL. PHPTAL templates are valid XML (and hence XHTML) files. You can farther use dummy content in PHPTAL and so get valid XHTML file with the final appearance, that can be processed and tested with standard tools. Here is a small example:

<table>
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <tr tal:repeat="users user">
      <td tal:content="user/first_name">Max</td>
      <td tal:content="user/last_name">Mustermann</td>
      <td tal:content="user/age">29</td>
    </tr>
  </tbody>
</table>

PHPTAL template engine will automatically insert all values from users array and replace our dummy values. Nevertheless, the table is already valid XHTML that can be displayed in a browser of your choice.

Vadim Ferderer
Very interesting, thanks for the idea.
Josef Sábl
A: 

I personally always use templating engines in php, python or whatever.

The first obvious reason already mentioned by others:

It's forces you to not use any business logic in your templates.

Yeah sure, discipline would do just fine, when you have it.

But this is just a tiny aspect of why you would use a templating engine. Most of them are more than just an engine and could be considered templating frameworks, whether you like it or not.

For example, Smarty also has advanced caching features like partial caching. Really useful stuff, things you would have todo all by yourself when using just php as templating language.

And please do not forget all those really useful helper functions just a quick search away in the docs. Most of them also provide an easy way to plugin your own functions and/or toolkit.

So yes, it's a matter of choice. When in need for really simple templating, consider showing some discipline a keep your logic out of your templates. But when you expect your application to grow, you will eventually be in need of template framework's features. And by then, you hopefully not reinventing the wheel by coding it all yourslef.

And last but not least, for me there is one killer feature available in some templating frameworks.

Template Inheritance

I've came to know it from Django and i'm now using it in the latest Smarty 3. The guys from the Symphony framework also have Twig, which you can consider a port with the Django syntax.

It's look a bit strange at first, but is extremely powerful. You build your skeleton and define various blocks. You can extend such skeleton and fill in (override) the blocks with your content.

For me that's a keeper!

Sander Versluys