It’s up there with the big questions of our time: How do we stop global warming? What happens after we die? Do we have free will? Can we cure AIDS? How do we bring peace and stability to the middle east? And, of course:

If PHP is a templating language, do we really need Smarty, Twig and other templating engines?

Yeah, I know, it’s a biggie. First of all, a brief explanation of what a templating engine is used for: In a MVC framework used for displaying webpages, the view contains the HTML of the page being rendered. A templating engine like Smarty or Twig is often used to render the view, the idea is that controller populates the view with data based on some logic or parameters - the goal is that the view should contain no logic or complicated code, that’s all in the controller. If we can call PHP code from inside an HTML file then why bother with Smarty etc? Well, here’s two snippets of a view, first one using PHP and then one using Smarty:
<h1><?php echo $title; ?></h1>
<div><?php echo $text; ?></div>
<?php if ($items): ?>
  <?php foreach ($items as $item): ?>
    * <?php echo $item ?>
  <?php endforeach; ?>
<?php else: ?>
  No item has been found.
<?php endif; ?>
and the same using Smarty:
<h1>{$title}</h1>
<div>{$text}</div>
{if $items}
  {foreach from=$items item=i}
    * {$i}
  {/foreach}
{else}
  No item has been found.
{/if}
Well, that’s great, the Smarty syntax is shorter, cleaner and easier to read. But, we already know PHP so what’s the point in introducing another syntax, and the real question: Do we need to use another templating syntax? Answer: it depends.

The decision to use a templating engine depends on who is maintaining the view and how disciplined they are.

If you work in a team where designers or other non-developers are modifying the HTML/CSS in the views then I think a templating engine is a must. It reduces the amount of code in the view, as we saw above, and makes it simpler for a non-developer to work with - it’s easy for the developer to print a list of the variables that are exposed to the view so that the designer can add the {$variable} tags themselves. If you’re in a developer-only team, or working by yourself then putting raw PHP in the view is OK. It’s faster as the template syntax doesn’t have to be parsed (although not that much faster as Smarty and Twig compile the template into PHP and cache that) and no-one needs to bother with a new syntax. But, if the developers are not disciplined then there’s a tendency to put more and more code and logic into view and it quickly gets messy. Not what you are using MVC for. Personally, I always use Smarty as I like its syntax and it comes with a good page-caching system built in. Works well with CodeIgniter too.