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.