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?
3 Answers
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.
- 52,936
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
- 4,978
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.
- 11