29

I develop my web applications using only PHP for the view files and I don't feel limited in any way, but I hear there's a consistent number of developers advocating "external" templating engines. So what do template engines offer that simple PHP lacks?

I'm looking for practical things, so I exclude the following:

  • babysitting bad developers (i.e. use a template engine because it forces you to not mix code into presentation)
  • conciseness of syntax (I have mappings in Vim for things like <?php echo $stuff; ?>, using curly braces wouldn't make any difference)
  • easier syntax for non programmers (I develop alone so that's not an issue)
0

10 Answers 10

23

New Syntax


Some people wont agree, but since I've been using Twig the "for ... else" feels right. It might not be a lot, but it keeps my templates that little bit cleaner.

{% for row in articles %}
 Display articles ...
{% else %}
 No articles.
{% endfor %}

Automatic Escaping


You can have the template engine automatically escape any output. This is great as you no longer have to repeat htmlspecialchars ... everywhere. Twig does this nicely.

{% autoescape on %}
  Everything will be automatically escaped in this block
{% endautoescape %}

Template Inheritance


Another feature I like is the ability to extend base templates. Here's a basic example

base.html template

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  {% block head %}
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}{% endblock %} - My Webpage</title>
  {% endblock %}
</head>
<body>
  <div id="content">{% block content %}{% endblock %}</div>
  <div id="footer">
    {% block footer %}
      &copy; Copyright 2009 by <a href="http://domain.invalid/">you</a>.
    {% endblock %}
  </div>
</body>

child.html template

{% extends "base.html" %}

{% block title %}Index{% endblock %}
{% block head %}
  {% parent %}
  <style type="text/css">
    .important { color: #336699; }
  </style>
{% endblock %}
{% block content %}
  <h1>Index</h1>
  <p class="important">
    Welcome on my awesome homepage.
  </p>
{% endblock %}

A child template can override blocks for page specific styles, content, etc ... You can also notice the use of {% parent %} which grabs the parents content so you don't lose it all while overriding.

I recommend you give Twig a go. Extremely useful.

4
  • 4
    Is it just me, or does that look a lot like Django templates? Feb 25, 2010 at 14:58
  • Might be, I'll have to see what Fabien has to say. Feb 25, 2010 at 15:27
  • I think its a lot of like Jinja templates.
    – hardik
    Feb 19, 2014 at 11:26
  • 1
    +1 on the for loop This looks utterly horrible in PHP and completely ruins the readability. Also the opening and closing tags of PHP all over the place destroy the nice look of HTML syntax.
    – John
    Sep 15, 2014 at 19:29
11

Separation of concerns.

This sort of things comes as standard when using a MVC/MTV approach - where the presentation of data is necessarily separated from the display of data, but not if you're using plain ol' PHP.

Using a template engine makes it easy to separate out what's being displayed from how it's being displayed.

I suppose you could argue that this falls under "babysitting bad developers", since a good developer ought to do this anyway, but in my view, a template engine makes it easier for good developers too.

6
  • 5
    This sounds like the baby sitting argument to me.
    – Ryan Bair
    Feb 25, 2010 at 14:34
  • 1
    separation of concerns is a good thing at all levels; but it doesn't necessarily means to have each 'concern' in a different file. That's only important if you have different teams working on the design and on the logic.
    – Javier
    Feb 25, 2010 at 14:49
  • 4
    @EvilRyry: It's more about engineering than baby sitting. Code does stuff, templates display stuff. The two are separate and unrelated. One should be able to change look without changing behavior. Really good PHP programmers might be able to do this, but a template engine makes it easier because you no longer have to sweat the details -- just hand data to the template engine.
    – S.Lott
    Feb 25, 2010 at 14:49
  • 1
    @EvilRyry - totally agree with what @S.Lott said. I consider myself a reasonably competent developer, but unless the architecture enforces good habits (such as separating out display of data from fetching of data), I'll get lazy, and muddle the two up. In other words, I for one need baby-sitting. Feb 25, 2010 at 15:00
  • 1
    @Javier - it's not completely necessary, but it sure is helpful. Feb 25, 2010 at 15:01
9

Easy switching between views

With the current state of the web, I need to provide my information in different formats:

  • A static html page
  • A dynamically loaded view on another HTML page
  • A JSON object of the data
  • An XML feed of the data, used in my flash part

The information for these formats can be equal, only the view differs. Using some sort of template engine, I can quickly switch between these views.

4
  • 3
    +1 - Think PC version and mobile version. This also makes it easier to style your pages differently for holidays or for special sales. Feb 25, 2010 at 14:38
  • 2
    Agree on "using some sort of template engine", doesn't answer why an external engine instead of PHP. Feb 25, 2010 at 15:40
  • External does not have to mean not PHP. Smarty is a pure PHP template engine built as a set of classes. And you could build your own template engine, the basic point is in use a template engine to seperate view from logic to make it very easy to show different versions of the view. Jan 27, 2011 at 9:30
  • Your view files might acctual qualify as a template engine if you are strict enough when building them but using a seperate engine can be faster and make you more efficient. Jan 27, 2011 at 9:31
3

With templates you can also delegate the resposibilitys of the presentation to designers. The designers can create templates, and the developers can work in the logic. It is also easier to keep the presentation consistent.

1
  • in my experience, this is the only valid reason. when working solo, it's easier to separate 'model logic' in its own file, and put 'view logic' at the top of each page's PHP, with the bottom for 'template PHP' code, with just one-liner variable and looping inserts.
    – Javier
    Feb 25, 2010 at 14:53
3
  1. I use my own "template" engine, quite basic stuff, assign value to [key] and the sorts.
  2. When I first looked for a template engine I found smarty, but it had so many security problems I ended up writing what I needed myself.
  3. You ask why ? because it has many features that can make your coding faster (stuff what you didn't think of and stuff you can delegate to the template system instead of your code)
  4. The majority of coders out there have chosen a template system and when working in a team you need to keep a standard.
2

If you'd like to develop applications that can be customized with a lot of different templates and layouts while keeping the design separated from the logic, e.g. for different customers, you may want to consider using a template system.

But if your applications just need one template and never change the layout a lot, then stick with what works for you, why change? :)

1

Some templating engines can compile templates leading to highly optimized transforms. Take for example the XslCompiledTransform in .NET.

1

Your non-answers look like real answers but phrased in a very condescending manner. For example:

babysitting bad developers (i.e. use a template engine because it forces you to not mix code into presentation)

I would call this an application of the Rule of Least Power. It makes your template much more useful for all users, not just "bad developers".

Restrictions are what make programming languages. PHP doesn't have an inline-assembly feature, and it's not because Rasmus thought you are all "babies".

0
1

I find myself using templating engines when I need sandboxing. for example, letting users of a hosted CMS edit templates.

1

First addressing the answers on here and the general background:

The primary reason people use them being is that that they usually make things a little more terse. It's questionable as to whether this is always a net benefit. The increased cogantive load of learning a new language and not having the flexibility of your host language at hand can eventually end up offerring more drawback than is offered by using a templating language. Twig in particular requires manually exporting core PHP functions to it. The best templating languages that seek to be terse would be better off instead extending PHP using the tokeniser.

Automatic escaping is another questionable feature. For a developer that codes very poorly, automatic escaping might be more secure but otherwise it weakens security, putting it out of mind and presenting the expectation that everything will be secure by default in any context. A really secure templating engine needs to know a lot about its context, sometimes this can't always be determined, only the programmer knows where something goes. If you need secure programming you need to have a developer that is not reliant on automatic escaping, period. This is also something that PHP actually can do, if you tokenize the PHP file you can separate raw text from PHP and wrap the PHP parts in output bufferring then apply any filter you like, so this is not a templating language exclusive feature.

Some templating engines can make pregeneration a bit easier and pre-compilation to make them faster, but this can be achieved with native templates as well. There's a necessarity to parse templates which often makes them less efficient and the process more complex for using them. The added complexity templates introduce is significant. This can often be abstracted away from you but will eventually come to bight you, for example caching issues (stale entries), performans issues, significantly more flutter and clutter when debugging, more layers and more code being excuted with much more that can go wrong, etc.

Many features such as extending templates you again do not need to use twig to achieve that. Similarly for things such as htmlspecialchars most people will create short helper functions for all of the functions they are using very frequently.

So where should you definitely use templating languages such as Twig?

  1. Baby sitting bad developers is sort of valid, although I'm not sure that they should be considered developers if you have to use something like twig to try to contain them. You'll also miffle good developers you'll wonder why they are being made to jump through hoops to achieve otherwise simple things.

  2. You might want to give templates to parties where you might want the HTML to be worked on but to not expose system internals, etc. This might be where you have a CMS for example, with users that can edit templates but are not the same as your developers. This related to the above but it's a more genuine case where you might have some benefit and that might be justified.

  3. A similar case is where you might want to use templates between systems, in this case a templating language can be a portable solution. This might not only be where you have multiple backends but where you have unusual architectural requirements such as the forward facing servers rendering views from data derived downstream. Take this further and you might want templates you can render frontend or backend. If you only have to ship data to frontend because it can render views itself, this can be more efficient. However you may also have to fallback to backend for various reasons.

  4. Another case is static analysis including across multiple languages. Most languages template effectively by string concatenation and arn't aware of the language you're producing. In some cases a templating language can provide a benefit when you can parse it fully, the language and the HTML. Another way to achieve this is to do your templating using HTML itself as much as possible to denote things, as in using classes, etc and the facilities HTML provides that can allow you to attach behaviour to things. A templating language can also be more parsable than PHP even if you're not able to also parse the language you're templating in. This can be used for optimisation or having templates that are more easily transpiled.

  5. Your language really isn't suited to creating HTML and other languages. PHP is a templating language so in most cases the use of a templating language does little but incur substantial drag. However if you're using something such as Java then you're very likely to desire a templating engine. Templating languages are a DSL, but if you already have a DSL that does what they do pretty well then it's YAGNI.

  6. Bespoke templating. Where you have a certain output format and domain that would significantly benefit from a customised templating language. This depends on your output format.

All of these cases are situation specific and not sufficiently common that a templating language should be used by default. Templating languages only address these points with varying levels of success (for example, many aren't HTML aware). If I were to rank Twig 10 out of 10 for how well it does each the average wouldn't be far off 5.

You can convert Twig into PHP but not PHP into Twig. This can sometimes be useful but it comes as a considerable cost as you lose a lot of the flexibility of PHP.

Of the small amount of Twig internals I've been exposed to the quality has also been poor, or has imported bad standards. For example the parser doesn't or at least didn't support perserving whitespace when I first tried it five years ago. I had a scenario where I needed to refactor, which meant I needed to be able to parse Twig, modify and output it again to rewrite code across thousands of templates, twig didn't support it and I had to rumage through the parser myself.

Similarly I recently investigated escaping for Twig. In particular the JS escaping stood out which supported escaping JS strings and other strange things rather than simply using json_encode. It's likely the custom escaping you'll get like that in frameworks is wrong. It's usually more reliable and secure to do it yourself (as long as you know about things like what happens if you JSON encode a string containing and template it as a javascript literal without sufficient escaping, for example).

In most cases the hundreds, sometimes thousands of lines of magic templating systems and other related systems implement for escaping, sanitising, etc are terrible practice, trying to guess your scenario or trying to cater to every possible one, adding more scope for bizarre bugs with data corruption, adding more chance of security blunders, etc. Usually you'll find the things like that in frameworks can be replace with a one or two line function that's more secure. You'll have other silly things as well sometimes like processing something over and over just in case because the framework is naive as to what you're doing where as if you make the things yourself you know exactly what you're doing and don't then have things like ending up sanitising the same string over and over.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.