Why should I use templating system in PHP? [closed]
Asked Answered
M

25

61

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:

PHP

<h1><?=$title?></h1>
<ul>
  <? foreach ($items as $item) {?>
  <li><?=$item?></li>
  <? } ?>
</ul>

Smarty

<h1>{$title}</h1>
<ul>
  {foreach item=item from=$items}
  <li>{$item}</li>
  {/foreach}
</ul>

I really don't see any difference at all.

Materially answered 12/1, 2009 at 16:37 Comment(4)
Thanks for every single comment you made. It helped me sort my thoughts. Now I am with Zend Framework and would recommend same for everyone. Now I see Smarty and the likes as the step to much more sophisticated, productive, challenging and fun world of framework development. No more mysql_queries and include_onces :-)Ezequiel
For one thing, you are using php short tags, which I agree makes things nice, but you will get ostracized from the PHP community for it. Compare <?php echo $foo ?> to {$foo} for a fair comparison, and then smarty clearly wins for readability.Calder
@Calder you will get ostracized from the PHP community for it - First, I heavily doubt on this account (many famous devs advocate short tags). Second, ... by the [scary academic] PHP community? Ain't we a bunch of fun-ease-dirt-loving barefoot kids playing in a sandbox?:) Disclaimer: I spent 6-8 years digging in PHP ignoring real beautiful and powerful programming languages and now I am 32 and really regret it! Violate PEP8 - that's where you'll get ostracized and it really would matter. PS. I dare to assume PHP's actual purpose at the beginning was templating system. No?Siobhan
As @Kornel noted here, there might be other reasons to use templating engine than cleaner syntax. Latte e.g. has very robust automatic escaping that would be almost impossible to implement correctly by hand.Ezequiel
S
26

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:

Surprint answered 12/1, 2009 at 16:46 Comment(9)
Yes, this exactly is the case of problem we have with Smarty. Feeding html code to smarty variables and using {php}{/php} tags.Ezequiel
This is something I've thought about a bit aswell. Can you give some examples of the things you might do in a 'view' (MVC context) in pure PHP? eg. text trimming, capitalisation, loops. Where is the line drawn for other 'concerns'.Shipping
@sanchothefat: I have the opinion of template languages that they all suck and don't entirely seperate ever in any implementation, you just have to draw your own line on a project-by-project basis. I'm working on having no code in my template, but thats a way off.Surprint
Display logic is always a slippery slope. At what point does zebra striping or text formatting become "real" logic? My opinion is that if you're asking yourself this question at all and not just saying, "aw screw it" you are on the right path.Laynelayney
@sanchothefat: Someone pointed out that you should never change any value inside the template. This is very reasonable minimum. I personally would go further, limiting PHP to only simple functionality. Not many chained commands.Ezequiel
Excellent answer. Templating systems are one of those things where you haven't paid your dues yet if you haven't written one yourself, only to throw it away later. It really boils down to what can you do consistently that's maintainable by those you work with ... and yourself.Enfield
This is the maintainable code you will be writing with smarty... seriously... I checked blame and something like it was written last week...::: {foreach from=$array|@array_keys item='key' }{foreach from=$array|@array_values item='value'}{if $smarty.post.var==$key}{$value|escape:'html'}{else}{$key|escape:'html'}{/if}{/foreach}{/foreach}Gray
The first link is broken.Steffaniesteffen
@Steffaniesteffen The page still exists, but the content has been deleted so only high rep people can view it. Given the deletion happened 6 years since I wrote this comment, I'm not sure how to resolve this, because you can't just replace a specific opinion :pSurprint
T
19

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.

Typhoon answered 12/1, 2009 at 16:54 Comment(4)
Excellent answer. The separation of logic and presentation is the biggest benefit. Allowing the design to change without worrying about the code increases productivity substantially.Bandit
This is all true, of course, but you don't need separate template engine to do that. PHP itself can be used the way you describe. Maybe it is my bad wording. I mean templating system as product not as approach.Ezequiel
The benefits of using 'off the shelf' software are the same here as anywhere else: you gain the benefits of prior testing by the community, ready documentation, and almost free maintenance going forward.Typhoon
YOU can implement separation of concerns yourself in pure php if you're disciplined, but as a project grows to having more developers, it'll become more and more of a task to make sure that your discipline applies to other developers/designers as well.Deckle
O
13

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.

Ourselves answered 13/1, 2009 at 13:32 Comment(0)
N
9

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:

<table>
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <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>
    </tr>
  </tbody>
</table>

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.

Noheminoil answered 20/1, 2009 at 0:34 Comment(0)
V
5

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; ?>
Vick answered 12/1, 2009 at 17:53 Comment(1)
It's really with escaping variables that php fails the verbosity game, which is why you have to write really really concise wrapper functions that and overall readability with just <?php } ?> end blocks, which will screw you.Deckle
H
5

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?

Heti answered 19/1, 2009 at 23:32 Comment(0)
R
4

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.

Rudimentary answered 12/1, 2009 at 16:44 Comment(2)
Ok, so this would be point 2 in my pros. You can always (at least in Smarty) inject templating engine with unsafe things. It is only a bit harder :-)Ezequiel
Then don't use Smarty :)Rudimentary
L
3

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
}
else
{
    // 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);
    $smarty->display("info.template");
}
else
    $smarty->display("error.template");

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.

Litigious answered 12/1, 2009 at 16:56 Comment(1)
This can also be done in PHP with include, but I guess that Smarty can do this more easily.Ezequiel
S
2

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.

Shipping answered 12/1, 2009 at 17:6 Comment(0)
A
2

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

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

Astaire answered 18/1, 2009 at 19:27 Comment(1)
In hindsight this is the best answer in the whole thread. Thanks!Ezequiel
L
1

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.

Lithium answered 12/1, 2009 at 16:48 Comment(0)
S
1

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.

Squeak answered 12/1, 2009 at 17:8 Comment(2)
Zend_View its a template engineHeti
I am now starting new project with Zend Framework, and it is like, wow, how could I do that without that before? :-)Ezequiel
R
1

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.

Rattling answered 12/1, 2009 at 17:39 Comment(0)
I
1

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.)

Inca answered 12/1, 2009 at 17:51 Comment(3)
Ok, but everytime I want to write something in Smarty, I reach for Smarty cheat sheet, thus not saving much of time :-)Ezequiel
@JS once you start using it every day you dont need to see the sheetHeti
I still need the cheat sheet after a year of using it because I run into ridiculous cases where it is [] instead of . Make up your mind smarty! Which is it?!?Gray
R
1
  • 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.

Rogozen answered 12/1, 2009 at 20:30 Comment(0)
P
1

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.

Paratuberculosis answered 12/1, 2009 at 20:34 Comment(0)
M
1

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.

Morgun answered 19/1, 2009 at 23:44 Comment(1)
but the designer could do that without smarty but with php too. just some words:P a foreach or an echo, right?Thirlage
B
1

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.

Bumblebee answered 27/11, 2013 at 9:10 Comment(0)
B
0

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.

Brilliant answered 12/1, 2009 at 17:12 Comment(0)
F
0

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!

Florentinoflorenza answered 15/7, 2010 at 22:38 Comment(0)
U
0

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.

Uniocular answered 4/1, 2013 at 5:36 Comment(0)
S
0

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.

Sheerlegs answered 6/4, 2013 at 19:40 Comment(0)
S
0

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?

Sago answered 17/3, 2014 at 16:47 Comment(0)
S
0

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.

Selfappointed answered 12/8, 2015 at 0:48 Comment(0)
D
0

Summarizing, I am adding a few of my thoughts. We should use templating system if it gives possibility to:

  1. cache & code compress
  2. provide some security layer (how variables are displayed)
  3. template inheritance and re-production of the code html (allow to avoid duplicate code)
  4. ability to write own plugins/modules for improve writing views
  5. "taking care" of translates problem and move this trouble to view layer (in Smarty there is no built-in module but there are good community solutions for this)
Dudek answered 4/1, 2020 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.