PHP as a template language

February 11th, 2010 by Ivo

It's been a while since I blogged, but I just ran into another zealot pointing me to NoSmarty.net when I mentioned templating.

I think I've said it before. The tool you use should depend on the job you're trying to do. So to say that Smarty is wrong just because it is, does not feel right.

I agree that in many cases PHP can be used as a template language just fine, but there are situations where a Smarty template (or any other templating engine) is just that more pleasant.

Here's a bit of template code that I encountered yesterday. Its use of php as a template language is hideous. Because it's a template for an xml message and because it needs to cope with systems with short open tags on and off, it looks like this:

 
<?php echo '<'; ?>?xml version="1.0" encoding="UTF-8"?>
<result processed="<?php echo $data["processed"]?"yes":"no"; ?>"
       <?php if (isset($data["orderid"])) { ?>orderId="<?php echo $data["orderid"]; ?>"<?php } ?> >
       <?php if (isset($data["error"])) { ?><error message="<?php echo $data["error"]; ?>" /><?php } ?>
</result>
 

Hideous!

Here's what it would look like in Smarty:

 
<?xml version="1.0" encoding="UTF-8"?>
<result processed="{if $data.processed}yes{else}no{/if}"
       {if $data.orderid} orderId="{$data.orderid}"{/if}>
       {if $data.error} <error message="{$data.error}" />{/if}
</result>
 

Yes, the first one is slightly more efficient, but the second one is actually readable for the average person.

Anybody claiming that <?php } ?> is 'just as convenient' as {/if} does not think clearly.

In my humble opinion, of course.

37 Responses to “PHP as a template language”

  1. February 11, 2010 at 5:48 pm, Ian Jenkins said:

    I concur :)

  2. February 11, 2010 at 5:52 pm, David goodwin said:

    I agree; although perhaps xhp changes things slightly; making php more suitable
    for templating tasks.

    The only problem with smarty is that it doesn’t escape output by default….

  3. February 11, 2010 at 5:58 pm, erik said:

    I agree completely, also because you can very easily restrict what can be used in smarty, which is handy when non-programmers have to touch it. But I do mostly prefer using php as a templating language, but only when I can use the PHP short tags and more template like syntax.

    IF ():
    ENDIF;

    FOREACH ():
    ENDFOREACH;

  4. February 11, 2010 at 6:03 pm, Dave Nattriss said:

    Excuse my ignorance, but why couldn’t you use ” instead of ” or ‘{/if}’ ?

    And instead of ‘<?php echo’ you can use ‘<?=’.

    At least, that’s what I do :-)

  5. February 11, 2010 at 6:10 pm, Matthew Weier O'Phinney said:

    The primary issue I have with using a template engine is that it adds vectors for error and degrades performance. Template engines require a parse/compile phase, adding to overhead — and the code they emit can also potentially contain parse errors. This adds complexity to debugging. Good template engines will have mechanisms for caching compiled templates in order to help reduce the performance hit, but there is still conditional logic associated with this that can be entirely circumvented if you simply just use PHP in the first place.

    That said, I see some places where template engines have a good fit: when you have separate UI and backend teams. In such cases, the UI engineers do not necessarily need to learn PHP, and the templating language prevents them from doing potentially bad things (such as using unfiltered input, or naive loops, etc.).

    I don’t think your rant that {/if} is easier than or is warranted, however; it’s all just markup.

    I agree, though: don’t bash smarty or other template languages just for existing; they do have their purposes, and the choice of what to use should be well considered.

  6. February 11, 2010 at 6:17 pm, Dave Nattriss said:

    Oh dear, your commenting mechanism seems to strip out code. That’s helpful…

    The first line was supposed to say the following, with ‘[' replacing '' instead of '[?php } ?>' or ‘{/if}’ ?

    And your example could just be this:

    [?= '[?xml version="1.0" encoding="UTF-8"?>'; ?>
    [result processed="[?= ($data["processed"] ? “yes” : “no”); ?>” [? (isset($data["orderid"]) ? ‘orderId=”‘ . $data["orderid"] . ‘”‘); ?>>
    [?= (isset($data["error"]) ? ‘[error message="' . $data["error"] . ‘” />’ : ”); ?>
    [/result>

  7. February 11, 2010 at 6:19 pm, John said:

    Here is what it would look like with a proper Data ViewHelper (without Smarty of course)

    resultNode($data) ?>

  8. February 11, 2010 at 6:53 pm, abc said:

    Anybody claiming that “foo”|bar:”baz” is ‘just as convenient’ as bar(‘foo’, ‘baz’); does not think clearly.

  9. February 11, 2010 at 6:54 pm, Ronald D. Willis said:

    I’m not a fan of the Smarty templating engine. Adding ANY code in any way, shape or form to a template file defeats the purpose of separating the content from the logic in my humble opinion.

    Give me the good ol’ XiTemplate object any day!

  10. February 11, 2010 at 7:12 pm, Avi Block said:

    I think the best compromise is going to come from facebooks new XHP extension

  11. February 11, 2010 at 7:33 pm, Kelvin Jones said:

    Understand that the decision to use a template system or vanilla PHP is a subjective one. It depends entirely on how you balance the pros and cons of each.

    To claim that people are not thinking clearly because they don’t agree with you is ridiculous.

    Personally, I think that the dialect/language that Smarty uses is ugly. That’s my opinion and it’d never find a place in my toolbox, but I understand that others may like using it.

    @Ronald – Your comment pangs of naïvety. I would have said something similar about 9 years ago. Google “presentation logic”.

  12. February 11, 2010 at 7:41 pm, Boy Baukema said:

    I wholly agree with Matthew here. If I had a nickle for every time I had to deal with Smarty caching problems… I would’ve been severely underpaid, but still made quite a bit.
    The overhead is something that simply shouldn’t be taken lightly.

    I would definitely use a template engine again if the requirements would allow admins to edit templates, but even though the syntax is ‘nicer on the eyes’ I wouldn’t otherwise use one.

  13. February 11, 2010 at 8:03 pm, Bill Karwin said:

    Like every other technology choice, it all depends on the requirements and priorities of each individual project.

    If performance is the top priority, the overhead of a template library can be unattractive. But few of us run websites on the scale of Facebook or Digg.

    But if runtime performance of server-side code is really the top priority, one should consider Java, or ASP.NET, or Python. Not trying to create a flame war, but benchmarks pretty consistently point to this conclusion.

    If on the other hand, your project places a priority on developer productivity, code readability/maintainability, reduced template language as guard-rails for non-programmers, then a template library shows its value.

  14. February 11, 2010 at 8:59 pm, Jordi Boggiano said:

    @David Goodwin: Dwoo (dwoo.org) handles auto-escaping and supports almost all Smarty features

    @abc: I fully agree, and you can do {bar(‘foo’, ‘baz’)} with dwoo, as well as {bar something=foo someblah=baz} (smarty style), or even mix to get some kind of python syntax if you got long argument lists: {bar ‘foo’, someArg=false} (admitting bar is bar($txt, $param=3, $param2=array(), $someArg=true)).

    Another point to be considered, which very valid imo, is that using a template engine limits most people in their temptation to inject logic into template. You can often do it, but it might not be as convenient as if you had plain PHP, so you start to think twice, and that is highly beneficial.

  15. February 11, 2010 at 9:04 pm, SM said:

    One of the reasons it’s horrible because some members of PHP group block any syntax sugar improvement that is proposed. Enabling {?= is still “controversial” at best, and many dream to kill it altogether and have only {?php echo. No wonder it doesn’t look nice – it is designed not to look nice! Why it is designed so I have no idea, but obviously some people like it that way and there’s enough those in PHP group to block any change for the better.

  16. February 11, 2010 at 9:55 pm, [MA]Pascal said:

    imho coding with php is cleaner,

    if you used correct indentation you wouldn’t have forgotten {/if} on your example,

    check my way/your way http://pastie.org/820738

    the only thing good in template system like Twig is the security systems embedded by default

    last thing, i think short tag should just be removed from php.

  17. February 12, 2010 at 12:38 am, SchizoDuckie said:

    @ work we use Blitz for templating.

    I must say, i’ve always been against templating systems and pro using pure php with variables, but blitz this is *the* most briliant templating system since sliced bread.

    It has all the features, blocks, repeating, if/unless , can use custom php functions inside templates, and it comes as a PHP extension, making it blazing fast.

    We use it for instance for http://www.soccerway.com :)

    Blitz: http://alexeyrybak.com/blitz/blitz_en.html
    (Works on win32 and linux)

  18. February 12, 2010 at 1:19 am, Herman Radtke said:

    I have been using PHP heredoc tags a lot to echo blocks of html/xml. This example if conditions, so it doesn’t help out that much. I generally try to handle all logic outside of my view to make testing easier as well.

    Example of how I do:
    <?php
    echo <<<EOT

    {$first_name}
    {$last_name}

    EOT;
    ?>

  19. February 12, 2010 at 1:20 am, Herman Radtke said:

    meh the comment section stripped all my xml tags in the heredoc block.

  20. February 12, 2010 at 8:00 am, Ivo said:

    @David: it cannot use

    @Ronald: the only logic in the template is presentation logic. If you can rewrite this without the if-statements, then show me. This is one of the biggest flaws of search/replace type templating, and one of the things where compiled template engines often offer a good clean presentation syntax.

    @boy: this not about problems smarty may or may not have, this is a counter argument to the ‘php is a template language, don’t use a template engine’ dogma.

    @SM: the php group does great things for us and most of it is done voluntarily without getting paid. Blaming them for this argument seems a bit harsh.

    @[ma]pascal: though your version looks better, the first line fails on systems with short open tags off, and the problem of hardly seeting the template because of the bulky php syntax still holds.

    @others mentioning ‘try template language X’: I’m not claiming Smarty is the holy grail (it’s far from it actually), but this is not about which template language is good or not, it’s about the benefits of using one over plain old php for templating. Which template engine is the best choice should depend entirely on your requirements.

  21. February 12, 2010 at 10:24 am, Artur Esjmont said:

    I totally agree that smary is much cooler than php templates. I even used to use it in cake to get rid of default templates and it was really great.

    on the other hand the example presented above is a bit extreme ; -) usually php views are no that horrible : )

    i am a fan of smarty and wish it was more popular so it would get better integration with frameworks etc.

  22. February 12, 2010 at 11:45 am, Tobias Struckmeier said:

    There are a ton of other reasons as well to use a template engine.

    You often need a sandbox for example.
    You want implicit output escaping. Eg. in the above example there might be a errormessage (which is generated somewhere else which simply contains invalid characters.
    Beside the readability there are many possibilities to improve the template code itself. Any template engine has shortcuts for common tasks, like iterations (with some modulo functionality build in and quickly accessible), list selection features (give me index of list or default) and others which handles issues when using php as a template language.

    My two cents :)

    Flame: But i think other template enginges are better than smarty which either have an xml syntax (TAL) and inheritance features like in django template engine :)

  23. February 12, 2010 at 2:19 pm, elzapp said:

    In general I agree with your post, but when you use php for templating it’s better to use some output than just the curly brackets, because it’s close to impossible to see what an } is ending when it’s used in templates.

    For my own personal templates I use the shortform opening tag for PHP tags, which makes it look even more clean.

  24. February 12, 2010 at 2:21 pm, elzapp said:

    lovely… your blog stripped the tags out… <?php if(…):?>something<?php endif?>

  25. February 12, 2010 at 4:45 pm, Seva Lapsha said:

    http://pastie.org/821906

  26. February 12, 2010 at 4:49 pm, Ivo said:

    @all: Grr, I cannot find a setting in wordpress to turn off the tag stripping. I’ll look into that later.

  27. February 12, 2010 at 4:56 pm, Matthew Turland said:

    I don’t care for Smarty personally, though I can understand arguments for its syntax sometimes being more readable and for security purposes, such as when application users are allowed to edit templates. If you have performance issues with Smarty, consider Blitz. Similar syntax, but implemented as a PHP extension in C. http://alexeyrybak.com/blitz/blitz_en.html

  28. February 12, 2010 at 5:32 pm, drm / Gerard said:

    Wow, this template discussion might surpass HipHop in the topic-of-the-month award in the PHP community ….

    Ivo, I wholeheartedly agree with your post. When I saw the replies on my own blogpost about Twig, I started pondering about starting a site “nonosmarty.net”, which would explain why *every* *single* point displayed on nosmarty.net is either biased or off topic. You point it out well: it is not about whether PHP as a template engine is wrong, it is about why another template engine would be a better fit for your needs. Emphasis is on “FIT”, not on “BETTER”.

  29. February 12, 2010 at 9:49 pm, Sugar Developer Blog » Blog Archive » Smarty or PHP as a templating language? said:

    [...] came across an interesting post by Ibuildings CTO Ivo Jansch, talking about the use of Smarty as a templating language over PHP [...]

  30. February 13, 2010 at 1:24 pm, Manes said:

    I agree with the point that the adoption of a technology depends on the business requirements: if you think Smarty is the right tool for the job when why not use it?
    Nevertheless, I don’t see why a developer shouldn’t look at the disadvantages of using such tool. I have never come across a website about any piece of software that lists its disadvantages and I am not surprised. I mean, why would you want to list the disadvantages of the product you’ve been working on? You don’t need a degree in marketing to answer this question.
    Perhaps some really frustrated developer took the trouble to create nosmarty.net, maybe when he chose Smarty as the templating engine to use in production he had only looked at the advantages of it, whereas back then he needed to look at the bigger picture and maybe today he would have been a lot happier had he not chosen Smarty.
    I have used Smarty in the past and I personally think it’s not bad, it did the job back then, but I wouldn’t use it again today, I’m looking at alternatives such as PHPTAL: the logic is tightly integrated with the markup thus forcing you to write clean XHTML. Isn’t that better? Plus, I saw Smarty code producing JavaScript code, XML feeds, documents later converted into PDFs. I know I am repeating myself, but when we all say we should use the right tool for the job, then why use Smarty to produce JavaScript code, XML feeds, documents? Any JavaScript library (Prototype, jQuery, etc.), the DOM extension and the PDF extension all seem to be better tools for the aforementioned examples.
    This is my humble opinion, feel free to disagree.

  31. February 13, 2010 at 3:16 pm, 網站製作學習誌 » [Web] 連結分享 said:

    [...] PHP as a template language [...]

  32. February 15, 2010 at 3:40 pm, PHP as a template language « Aljo Guts said:

    [...] Latest news) One of the great debates in the world of PHP – is the language by itself a good templating language (versus using something like Smarty)? I think I’ve said it before. The tool you use should [...]

  33. February 15, 2010 at 3:55 pm, Hirvine said:

    True, about messed up PHP, but your example actually shows a poor controller.
    A controller shouldn’t use the same view for an error and valid xml.
    On the other hand, if I don’t retain the `error` message idea, you may tell blank error message is no error. Which would preserve a single view. Short-tags is indeed irritating here. Mine would look like.

    Valid

    <result processed=”processed? ‘yes’:'no’; ?>”
    <orderId=”orderid; ?>” />

    Error

    <result processed=”processed? ‘yes’:'no’; ?>”
    <orderId=”orderid; ?>” />
    <error message=”error; ?>” />

    It also fixes your missing ‘<’ in front of the order id element.
    You have also missed the self closing slash on order id element.

    Clearly Smarty didn’t helped you to find those format errors. So no “Easy to Use and Maintain” story for Smarty.

    Hey don’t get me wrong. It is what @Manes tells. Using smarty is depended by situation and business. Among friends PHP would do the trick, among a big business which uses different frameworks/cms you may think using template systems.

  34. February 15, 2010 at 3:57 pm, Hirvine said:

    ah form removed my php tags completely, but you get the idea I think :)

  35. April 11, 2010 at 5:27 pm, Fedor said:

    Smarty sucks!!! So much code for so little.

  36. July 30, 2010 at 6:51 pm, Faltzer said:

    Smarty is terrible; any templating engine that effectively evaluates PHP code is bad anyway. Hence why SUIT is better suited for the purpose of templating, because there is true separation of logic involved, and far less chance of security being compromised should an attacker gain access to your templates.

  37. November 03, 2010 at 7:44 am, Tomasz Jędrzejewski said:

    In my opinion, if we decide to use other-than-PHP template language, we should choose something that really helps, not just replaces to { … } like Smarty does. Such template engines not only don’t solve any problems, but also introduce new ones by their esoteric syntax and limitations. I.e Smarty 2 could not execute normal expressions in normal way, but forced to use some weird replacements like {math} instruction or “modifiers”, not mentioning complete lack of tools for making modular templates. These drawbacks are fixed “now”, in Smarty 3, 5 years after other template engines noticed the need to introduce such things!

    Some logic is always necessary in templates, it cannot be fully separated, unless we want to have 19281 templates for the same page, for every possible case. The point is to understand what is a presentation logic and what is business logic. The first one in templates is OK, second one – not. Template engines should ease writing presentation logic by introducing specialized instructions etc. not just give loops, ifs and that’s all. Good examples that there is another way are PHPTAL and more advanced Open Power Template 2. Both of them use XML templates, validate template syntax on the fly, and provide some high-level abstractions to the ordinary control programming structures which simplifies writing templates. In OPT, the template is even separated from the real nature of data passed from PHP to it, i.e. you do not have to worry if this is an array, object or something else, and if it is a loop, how the sub-rows are actually represented. In pure PHP and Smarty this is hardly possible.