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?
What are the advantages of using a template language?
php;mvc;cakephp
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.