PHP as a template language
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.
Tags: smarty, templates, templating



February 11th, 2010 at 5:48 pm
I concur
February 11th, 2010 at 5:52 pm
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….
February 11th, 2010 at 5:58 pm
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;
February 11th, 2010 at 6:03 pm
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
February 11th, 2010 at 6:10 pm
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.
February 11th, 2010 at 6:17 pm
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>
February 11th, 2010 at 6:19 pm
Here is what it would look like with a proper Data ViewHelper (without Smarty of course)
resultNode($data) ?>
February 11th, 2010 at 6:53 pm
Anybody claiming that “foo”|bar:”baz” is ‘just as convenient’ as bar(’foo’, ‘baz’); does not think clearly.
February 11th, 2010 at 6:54 pm
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!
February 11th, 2010 at 7:12 pm
I think the best compromise is going to come from facebooks new XHP extension
February 11th, 2010 at 7:33 pm
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”.
February 11th, 2010 at 7:41 pm
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.
February 11th, 2010 at 8:03 pm
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.
February 11th, 2010 at 8:59 pm
@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.
February 11th, 2010 at 9:04 pm
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.
February 11th, 2010 at 9:55 pm
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.
February 12th, 2010 at 12:38 am
@ 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)
February 12th, 2010 at 1:19 am
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;
?>
February 12th, 2010 at 1:20 am
meh the comment section stripped all my xml tags in the heredoc block.
February 12th, 2010 at 8:00 am
@David: it cannot use < ?= as it needs to work on systems with short open tags disabled, as mentioned in the post.
@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.
February 12th, 2010 at 10:24 am
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.
February 12th, 2010 at 11:45 am
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
February 12th, 2010 at 2:19 pm
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.
February 12th, 2010 at 2:21 pm
lovely… your blog stripped the tags out… <?php if(…):?>something<?php endif?>
February 12th, 2010 at 4:45 pm
http://pastie.org/821906
February 12th, 2010 at 4:49 pm
@all: Grr, I cannot find a setting in wordpress to turn off the tag stripping. I’ll look into that later.
February 12th, 2010 at 4:56 pm
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
February 12th, 2010 at 5:32 pm
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”.
February 12th, 2010 at 9:49 pm
[...] came across an interesting post by Ibuildings CTO Ivo Jansch, talking about the use of Smarty as a templating language over PHP [...]
February 13th, 2010 at 1:24 pm
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.
February 13th, 2010 at 3:16 pm
[...] PHP as a template language [...]
February 15th, 2010 at 3:40 pm
[...] 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 [...]
February 15th, 2010 at 3:55 pm
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.
February 15th, 2010 at 3:57 pm
ah form removed my php tags completely, but you get the idea I think
February 15th, 2010 at 4:01 pm
[...] to his blog talking about 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 [...]
February 15th, 2010 at 8:08 pm
[...] to his blog talking about 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 [...]
April 11th, 2010 at 5:27 pm
Smarty sucks!!! So much code for so little.