Why should I use templating system in PHP?

Why should I use templating system in PHP?

The reasoning behind my question is: PHP itself is feature rich templating system, why should I install another template engine?

The only two pros I found so far are:

  1. A bit cleaner syntax (sometimes)
  2. Template engine is not usually powerful enough to implement business logic so it forces you to separate concerns. Templating with PHP can lure you to walk around the templating principles and start writing code soup again.

... and both are quite negligible when compared to cons.

Small example:


  <? foreach ($items as $item) {?>
  <? } ?>


  {foreach item=item from=$items}

I really don't see any difference at all.


Yes, as you said, if you don't force yourself to use a templating engine inside PHP ( the templating engine ) it becomes easy to slip and stop separating concerns.

However, the same people who have problems separating concerns end up generating HTML and feeding it to smarty, or executing PHP code in Smarty, so Smarty's hardly solving your concern separation problem.

See also:

The main reason people use template systems is to separate logic from presentation. There are several benefits that come from that.

Firstly, you can hand off a template to a web designer who can move things around as they see fit, without them having to worry about keeping the flow of the code. They don't need to understand PHP, just to know to leave the special tags alone. They may have to learn a few simple semantics for a few tags but that is a lot simpler than learning the whole language.

Also, by splitting the page into separate files, both programmer and designer can work on the same 'page' at once, checking in to source control as they need, without conflicts. Designers can test their template visuals against a stable version of the code while the programmer is making other, potentially breaking changes, against their own copy. But if these people were both editing the same file and had to merge in different changes, you can encounter problems.

It also enforces good programming practice in keeping business logic away from presentation logic. If you put your business logic mixed in with the presentation then you have a more difficult time extracting it if you need to present it differently later. Different modes of presentation in web apps are increasingly popular these days: RSS/ATOM feeds, JSON or AJAX responses, WML for handheld devices, etc. With a template system these can often be done entirely with a template and no or little change to anything else.

Not everybody will need or appreciate these benefits however. PHP's advantage over Java/Python/Ruby/etc is that you can quickly hack up web pages with some logic in them, and that's all well and good.

Using non-PHP templates with the excuse of separating logic is nonsense. If the developer doesn't understand what the business-view logic separation is and how it should be done, then the problem must be addressed appropriately. Otherwise you end up with HTML in business logic or business logic in templates -- no templating engine is going to save you. You have to teach the developer the basics.

And if the developer does understand that, the templating system is only a limitation. It doesn't add any value to the development process, only overhead of learning a new syntax, keeping another library up to date, and slower execution. While the latter can be solved with caching and whatnot, this only remedies a problem that otherwise wouldn't exist. So, templating systems offer no value, no advantage at all.

There is one exception, though, where I think using a non-PHP templating system is reasonable: when view-logic programmers must have limited access to the templates. For example if you're a provider for a blog-hosting system and you want to allow your users to personalize and code their templates, without allowing them to execute arbitrary code. This argument, however, does not apply to cases where a designer is willing to learn a little code to help programming the UI. If he can learn Smarty, he can surely learn PHP.

There is still a good reason for a template system to use, however not Smarty, but PHPTAL. PHPTAL templates are valid XML (and hence XHTML) files. You can farther use dummy content in PHPTAL and so get valid XHTML file with the final appearance, that can be processed and tested with standard tools. Here is a small example:

      <th>First Name</th>
      <th>Last Name</th>
    <tr tal:repeat="users user">
      <td tal:content="user/first_name">Max</td>
      <td tal:content="user/last_name">Mustermann</td>
      <td tal:content="user/age">29</td>

PHPTAL template engine will automatically insert all values from users array and replace our dummy values. Nevertheless, the table is already valid XHTML that can be displayed in a browser of your choice.

for me, one of the big features of templates engines is that the cache layer its transparent for you. I've been using smarty long time ago, and the cache stuff make the life easier. also the smarty design allow you to use your own cache function. In my case I choose if for some page should use memcache or disk to store the template output.

in the other hand if your site has a big traffic and you dont know how to manage smarty and tuning it well this any template engine could be a site killer. but even not using smarty your site can die also.

flickr is currently using smarty. its shouldn't be soo bad, isn't?

PHP is pretty much a templating system. The key is to force yourself to separate logic from presentation on your own. Using Smarty or something like that only makes it slightly more inconvenient to mix logic and presentation. If you can't make yourself separate them on your own, using a templating system isn't going to help. All it's going to do is eat up additional processing power.

The key is to not alter any values in your presentation code. To do this, I think PHP itself is just as effective as Smarty if you use the if/endif syntax:

<?php if($some_test): ?>
   <em>Some text!</em>
<?php endif; ?>

Mostly I think to avoid any "unsafe" backend logic to be applied in templates. Since most of the times templates are handed to designers, we only want to give them a closed set of things they can do.

I like the ability to trivially display any template from any PHP file (and include fragments of templates inside each other, for common elements like nav bars). For example, suppose you had a page that normally prints some information if you're logged in or an error if you're not. With PHP, you'd write something like:

if (loggedIn)
    // print lots of HTML here
    // print error message

In Smarty, it could be something like this (forgive my probably wrong syntax, it's been a while):

if (loggedIn)
    $smarty->bind("info", someObject);

If you were really clever, you could even display the login page template instead of the error template, optionally with a message explaining why the user ended up there. And if you went with the technique as I wrote it and then decided you wanted to switch to displaying the login box, it's only a single line change! For me, it's not just about keeping the separation of view and logic, but about the ability to reuse common elements of the view from many places.

I'm happy using an MVC framework like code igniter. I find that in the 'views' I tend to stick to php code that relates only to how values are displayed. I have a library of formatting functions i can use in the views to that effect. One of the premises of code igniter is to avoid a templating language because of the way it can restrict you and the slow down incurred.

I find that is better for designers to learn some PHP, so that they can achieve what they need to do eg. alternating class names. It will also make them more useful in the long term and it's not a huge leap from one syntax to the other.

You forgot htmlspecialchars() twice. That's why you need templating system.

Smarty is poor. Don't judge templating systems based on that.

Your analysis is reasonable. I suppose:

  • Template designers and back-end programmers may not be one in the same, so it promotes separation.
  • It protects you from yourself somewhat in that you can't really do "too much" PHP in your templates.
  • It may be easier to optimise/precompile templates in some scenarios? (This is speculation)

Personally, I think they're more hassle than they're worth. Particularly they don't work if you want to hand the templates to "designers" since the WYSIWYG tools don't know what to do with them.

One template engine advantage that I didn't see was the possibility of dynamic html elements - something like asp.net controls. For example, with PEAR's HTML Template Flexy you can have dynamic form elements that automatically maintain state. A regular html select element can be populated and have the selected item set in the code behind without loops or conditionals in the template.

I think that cleaner syntax is quite a big win. Although it may look like only a few characters, but when you do it every day, then each character starts to count.

And {$myvar|escape} is IMHO quite a bit shorter than <?php echo htmlspecialchars($myvar); ?>. (Keeping in mind that <?=$foo?> syntax is only available when it is specially enabled in PHP conf.)

I don't think you should use a template engine. Instead you should use something like Zend_View which encourages you to do separate logic from presentation, but allows you to build your presentation layer in PHP.

  • You want to use a file with PHP code as a template? Fine.
  • You want to use your variables in said template? Fine.

Just remember to separate logic and final output (presentation). This is better accomplished with a templating framework. But you dont have to learn something like Smarty.

  • If you use Zend_View or similar you can use PHP code all the way.

Many people here have the correct reply. Smarty is not templating in PHP. Far from it. Smarty is there mostly for those who have to use designers (ie non-programmers) to edit and setup the display of pages. If everyone who are gonna change the layout of your pages can program, you can go with a more PHP code oriented templating system. But you really should have all your output data ready and send it to the template. If you let each page fetch, process and display the content, you will have to refactor it sooner then later.

When you're writing code for someone else. For example, I was once involved in the creation of a rigid web application framework that should be customizable for our customers. One important request was that the customer could hire a designer to modify the templates without having to be able to program. Even more important, he might not be authorized to change the code.

Smarty for example allows to implement quite rigid restrictions on what the template may do. Basically, our application disabled all but the most basic code constructs and a selected set of modifier functions. So we had two goals that were served well by a template engine: simplicity and security.

And let us not forget the future. Websites are old almost the minute they are published. You WILL need to update the look and feel at some point. If you maintain separation often times a designer alone can complete a whole new website with the same programming on the back end. This allows for faster and cheaper redesigns, allowing you to only involve the programmer if new functionality is required.

Some might argue that Smarty does what PHP can do already: separate the presentation from business logic. The PHP programming language is great for code development but when mixed with HTML, the syntax of PHP statements can be a mess to manage. Smarty makes up for this by insulating PHP from the presentation with a much simpler tag-based syntax. The tags reveal application content, enforcing a clean separation from PHP (application) code. No PHP knowledge is required to manage Smarty templates.

The importance of this separation is situational. It is commonly more important to web designers than it is to PHP developers. Therefore, Smarty is commonly a good fit when the roles of developers and designers are separated. There is no right or wrong answer: every development team has their own preferences for managing code and templates. Aside from a clean tag-based syntax, Smarty also offers a wide variety of tools to manage presentation: granular data caching, template inheritance and functional sandboxing to name a few. Business requirements and the PHP code Smarty is being used with will play a large role in determining if Smarty is a good fit.

I'd wager that if a PHP template language was so coercive as to force you to use it, you wouldn't use it at all. The ability to 'jump out' and do things your way when in trouble is one of the attractives of PHP.

I don't say that it's a good thing, nor that the code will be maintainable, just that in the initial considerations, I wouldn't choose a template language that blocked me completely.

Otherwise, I agree that templating systems help you divide work between coding and design, and possibly letting designers design and the coding to us.

I personally always use templating engines in php, python or whatever.

The first obvious reason already mentioned by others:

It's forces you to not use any business logic in your templates.

Yeah sure, discipline would do just fine, when you have it.

But this is just a tiny aspect of why you would use a templating engine. Most of them are more than just an engine and could be considered templating frameworks, whether you like it or not.

For example, Smarty also has advanced caching features like partial caching. Really useful stuff, things you would have todo all by yourself when using just php as templating language.

And please do not forget all those really useful helper functions just a quick search away in the docs. Most of them also provide an easy way to plugin your own functions and/or toolkit.

So yes, it's a matter of choice. When in need for really simple templating, consider showing some discipline a keep your logic out of your templates. But when you expect your application to grow, you will eventually be in need of template framework's features. And by then, you hopefully not reinventing the wheel by coding it all yourslef.

And last but not least, for me there is one killer feature available in some templating frameworks.

Template Inheritance

I've came to know it from Django and i'm now using it in the latest Smarty 3. The guys from the Symphony framework also have Twig, which you can consider a port with the Django syntax.

It's look a bit strange at first, but is extremely powerful. You build your skeleton and define various blocks. You can extend such skeleton and fill in (override) the blocks with your content.

For me that's a keeper!

template management system, we can manage the template files separately. system execution time will be faster then normal PHP project. so here PHP files and template files are separately maintained.

once run the files the code will be saved it template_c. so its not compile many times.

I several times used tinybutstrong, which has a pretty neat and simple syntax. No loops or pseudocode in the html template.

From their homepage:

TinyButStrong is a library that enables you to dynamically create XML/HTML pages and any other files based on text source. It's a Template Engine for the PHP language. It enables you to easily display information from your database, but also to seriously harmonize and simplify your PHP programming.

TinyButStrong is oriented to HTML but not specialized to Html. This means it can work as well with Text files, XML, RSS, RTF, WML, Excel (xml), ... The OpenTBS plug-in enables your to merge OpenOffice and Ms Office documents.

Developers who will make use of OOPs concepts heavily,like JAVA/Spring/Oracle PL-SQL people,they say that PHP language itself is used for presentation/view/display logic in the Enterprise level projects. In these BIG projects the backend is Oracle,the database is fetched using pl-slq/java and presentation is php.The best example is facebook.http://en.wikipedia.org/wiki/Facebook facebook uses php for presentation, java/c++ as backend interface.

The only reason php is used as presentation because it works closely with HTML,but java/c++ is more OOPs based and can't be fit directly with HTML. Tell me one CMS(joomla/drupal/wordpress) or framework(zend/symfony/Yii) which makes use of Smarty? So WHY smarty is necessary?

I like using templates for a couple of reasons:

1) It cleans up the readability of the PHP code. My PHP files become bloated and ungraceful when there are print("") statements with chunks of HTML everywhere. Also, issues crop up like how do you pass variables into the HTML text? Do you use tags everywhere? Do you use print("") and escape your HTML quotes and concatenate your variables? Do you use print("") and use single quotes in HTML, going against the standard, and insert your variables directly?

2) It cleans up the presentation of the HTML code. It can become hard to keep your generated HTML looking good if it is cut and hacked to pieces across multiple files. For example, your indenting can get way off.

3) It allows you to create multiple templates, and then a logged in user can select which template/skin he wants to display when browsing your website, and you can also quickly and effortlessly change the default template to something else if you're so inclined.

Overall, it's just a better way of organizing everything. There is a little bit of tradeoff in having to learn and type template class commands, open multiple files, etc. But in my opinion I think it is worth it because the code's readability and organization goes up.

Need Your Help

__udivdi3 undefined — how to find the code that uses it?

c linux linux-kernel kernel

Compiling a kernel module on 32-Bit Linux kernel results in

Run a string as a command within a Bash script

bash shell command-line-arguments

I have a Bash script that builds a string to run as a command