2

I work on a CakePHP app and the views consist of raw html with embedded php echo statements, which over time has gotten rather messy. Before I go in and rewrite the code, I'm wondering if it makes sense to rewrite the views with a template engine, such as Twig or Smarty, but I don't have experience with template engines. What are all the advantages of using a template engine?

dandrews
  • 123
  • 1
  • 5

3 Answers3

9

Yes, definitely worth it.

While PHP is sort of a template language, the syntax is, as you have observed, clumsy and does not help readability much. Short tags alleviate the verbosity a bit, but as soon as conditionals and iteration come into play, things do get messy.

Also, PHP does not take care of encoding output for you; if you do the following:

<a href="<?= $_GET['some_url'] ?>">Click here!</a>

...then you have yourself a big fat XSS vulnerability; a proper template engine defaults to HTML-encoding any variables you interpolate, unless explicitly overridden. This means you can't accidentally run into this common security pitfall.

With these two in mind, compare:

<ul>
    <?php foreach ($items as $item): ?>
    <li><a href="<?= htmlspecialchars($item['url']) ?>"><?= htmlspecialchars($item['title']) ?></a></li>
    <?php endforeach; ?>
</ul>

vs.:

<ul>
    {%foreach items as item%}
    <li><a href="{item.url}">{item.title}</a></li>
    {%end%}
</ul>

Another advantage, more a psychological one than technical, is that a template engine enforces (or at least strongly suggests) that you keep you presentation code separated from application logic.

One thing to keep in mind, though; PHP was not intended for writing parsers and such, and so template engines written in pure PHP can be quite slow. Some of them are implemented in a more suitable language and exposed as PHP modules; you may also find others that can compile to raw PHP, which, once compiled, can be called directly.

tdammers
  • 52,406
  • 14
  • 106
  • 154
  • Is the syntax in your example from a particular template engine? – dandrews Sep 18 '12 at 22:08
  • @dandrews: It's a hypothetical language, but it's close enough to existing ones. – tdammers Sep 19 '12 at 05:21
  • Excellent overview, and +1 specifically for the presentation code / application logic split comment. I cringed slightly remembering inline SQL statements, which seemed to be the "norm" a few years back. – Daniel B Sep 19 '12 at 07:42
  • 2
    Comparing bad plain PHP and good template code is not fair. If you validate input in the application logic, use the [alternative syntax](http://www.php.net/manual/en/control-structures.alternative-syntax.php) and create safe output functions with short names, plain PHP would look much cleaner. It might not be as good as template syntax, but the difference would be smaller. I agree with the psychological point anyway. – lortabac Sep 19 '12 at 09:36
  • 1
    @lortabac: none of my examples do any input validation, because that's outside the scope of templates. A shorter output function name (e.g. aliasing `htmlspecialchars()` to `h()`) reduces typing effort, but doesn't take the security/convenience problem away: it's still equally easy to forget the html-encoding. I've added the alternate syntax to my example, but IMO it doesn't do an awful lot to increase readability. – tdammers Sep 19 '12 at 13:38
  • 1
    Templates are a good way to get started with separation of concerns, but once you know your way around this concept I would leave out template engines altogether: first there is overhead in compiling the templates back to php (which may or may not be cached, but still), second you have to learn a pseudo-language to do things you could already do with php itself, and third, is there really that much difference between `` and `{%foreach items as item%}` or between `{var}` and `=$var?>` for that matter, other than a few characters? – Mahn Sep 21 '12 at 18:04
  • Also you would normally not sanitize or process data in your view, but in your controller. If you process and format your data in the controller and let the view have as little logic as possible, you'll find it is not all that verbose for templating purposes. But yes, if you find yourself using htmlspecialchars() in your views by all means use a template engine. – Mahn Sep 21 '12 at 18:05
  • 1
    @Mahn: html-encoding belongs in the view, not the controller. The controller should not care at all what the output format is; it could be HTML, JSON, plain text, EBCDIC-encoded INTERCAL source code, it shouldn't matter. The controller hands raw data to the view, and the view takes care of massaging it into the correct format for presentation. HTML-encoding is not data processing, it's presentation logic, and it does belong in the view. – tdammers Sep 22 '12 at 09:43
  • @tdammers it sounds as if you were skipping the role of the controller in your schema but I suppose it depends on how one implements MVC. I would definitely not format the output in the view in a schema where the view is supposed to represent the final template, thin controllers and fat views don't sound right to me, to but to each one its own. – Mahn Sep 22 '12 at 10:34
0

I have been using MVC design pattern for a few years.

MVC allows you to separate your business logic (Model) from your user interactions (controller) and templates (views). I've worked with Zend_View for a long time, and I wouldn't use a template engine with it. http://framework.zend.com/manual/1.12/en/zend.view.html

DeveloperDon
  • 4,958
  • 1
  • 26
  • 53
-1

Im my opinion, a template engine is only worthwhile if your project requires the ability for users to create custom themes. You spent a lot of years learning PHP right? Unless you want other "non php" people to edit the theme then just use PHP in the layouts. A templating engine takes time to learn, and adds an additional overhead to your script.

  • 1
    I know Python far better than any templating language, but outputting HTML (for instance) from Python is awful using just `print` without a lot of declarative support code (allowing things like `with tag('p'): text('Hello world')`, and that's actually much prettier than any real output code I ever wrote), and even then it doesn't close to the clarity and clutter-freedom of a good templating language. Have you ever used a good templating language? It's a bliss! –  Sep 18 '12 at 18:41
  • 1
    "Takes time to learn" is not, in itself, a good reason to not consider using something. Furthermore, I would be interested in what your profiler reports say about the "additional overhead" you claim exists. – user16764 Sep 18 '12 at 19:56
  • i think he meant "additional overhead" as far as maintenance is concerned. If you have to train new employees to use the template even tho they already know PHP, that's overhead. But I still don't necessarily agree with this answer as it currently stands. – David Peterman Sep 19 '12 at 15:33
  • User16764 - I have no idea what my profiler says, as I don't use templating engines unless the project requires non coders to be able to edit layouts. Logic would say though that any additional scripts require extra processing power/time even if it is only a small amount. I use a strict MVC coding pattern, usually under codeigniter so the only PHP that ends up in my views is if/else statements and loops. With the use of alternative syntax the code in views amounts to the same if not less than template syntax and I didn't have to waste productive money earning hours learning something else – Liam O'Neill Sep 19 '12 at 20:01