Slashdot Mirror


PHP Template Engines?

kubed asks: "I've recently learned how to use PHP template engines to separate business logic from presentation. Some argue that template engines make applications easier to maintain and make for cleaner code. Others argue that template engines introduce unnecessary overhead and require too much additional processing power. Do the readers of Slashdot think that it is important to use templates or are they just an extra unnecessary layer? There are dozens of PHP template engines to choose from including Smarty, phplib, and bTemplate. Which template engines do you have experience with and which ones have the best performance?"

14 of 90 comments (clear)

  1. Template Engines are good by Alpha27 · · Score: 5, Informative

    At present, I am using Smarty with my php programming and find it to be a very good product. It has a number of features built in to make programming easy and quicker for me. Previously I've used HTML::Template for Perl, and have to say I prefer a templating engine when the application I'm building becomes large enough.

    The advantages:

    • The code is cleaner, allowing me to find bugs easier, and not run into annoy issues of types that may occur when using print statements to join HTML with PHP output
    • The separation allows for more than one person to work on the same task. While a programmer is programming, the design can design at the same time, with little input from the programmer. Once all the variables in place, the designer only needs to do their part.
    • Smarty has a builtin caching system, so that's another thing you don't have to worry about

    Is there an overhead, probably, but Smarty does a number of things to help bring it down. So far, I find it to be more efficient than a case of not using a template engine.

    There are so many advantages to using a template engine, that it will probably outweight some of the disadvantages you will encounter.

  2. not ready for use yet, but worth looking by mkavanagh · · Score: 1, Informative

    phpBB 2.2 has a great, fast templating/styling system that's vaguely a hybrid of phpLib and Smarty. Not stable yet, but worth remembering for the future.

  3. My experiences by DamienMcKenna · · Score: 2, Informative

    Last year I wrote a large content and ecommerce system using PEAR::DB and Smarty. Smarty was wonderful but I should have used ADOdb as the database abstraction layer. At my current job I use Fusebox 3 which I find to be a better way of approaching the problem as you are dividing up the entire application into bite-sized pieces. From there I just use straight HTML rather than a templating layer. I personally wish I knew about Fusebox 3 last year as my content system was 80% the same architecture, so I could have saved myself the R&D time.

    Damien

  4. Beyond the Template Engine by chmouel · · Score: 5, Informative
    You may be interessed to read this article :

    http://www.sitepoint.com/article/1218/

    About (in the opinion of the article author) the superiority of smarty.

    Introduction of the article :

    In general, template engines are a "good thing."

    I say this as a long time PHP/Perl programmer, user of many template engines (fastTemplate, Smarty, Perl's HTML::Template), and as author of my own, bTemplate.

    However, after some long discussions with a co-worker, I've decided that the vast majority of template engines (including my own) simply have it wrong. I think the one exception to this rule would be Smarty, although I think it's simply too big, and considering the rest of this article, pretty pointless. There are, however, a couple of reasons why you might choose Smarty (or a similar solution), which will be explored later in this article.

    This article discusses template theory. We'll see why most "template engines" are overkill, and finally, we'll review a lightweight, lightning fast alternative.
  5. TAL by Earlybird · · Score: 5, Informative
    Quoth the original poster:
    • Some argue that template engines make applications easier to maintain and make for cleaner code. Others argue that template engines introduce unnecessary overhead and require too much additional processing power. Do the readers of Slashdot think that it is important to use templates or are they just an extra unnecessary layer?

    There's no single answer. Like anything else, it depends on your application.

    Templating gives you the flexibility of being able to change the look of the pages independently of the information it represents. Templating requires more planning and design, since it's part of a feedback loop that affects how the information is shaped.

    For some applications, separating the presentation logic from the application logic is simply a necessity, and the pains taken to design around a template system is an investment from which you will reap the benefits later, either when you change the application logic or the presentation logic.

    (Separation of application interfaces from application logic is usually equally important, not the least because it allows refactoring, ie. the continuously improvement of code without affecting interface compatibility.)

    • There are dozens of PHP template engines to choose from including Smarty, phplib, and bTemplate. Which template engines do you have experience with and which ones have the best performance?

    I don't know any of them, as I don't use PHP unless forced to, so no comment on that. However, I have used a lot of template systems in my time, and the best one I have had the pleasure of working with so far is TAL.

    TAL (Template Attribute Language) was originally implemented for Zope. It is, however, completely general, and has been enthusiastically received by the open source community, spawning several implementations, including an implementation for PHP.

    One of the core ideas of TAL is that it's valid XML, and therefore valid XHTML, and it's designed in a way to does not intrude on the original markup. You can view a TAL template in a WYSIWYG editor like Dreamweaver, and it will look fine; moreover, if the template is well-written, it may even look like a static preview of the real, dynamically generated template.

    TAL is in fact just one part of a trinity that also includes TALES (TAL Expression Syntax) and METAL (Macro Extensions for TAL).

    TAL specifies the template structure. TALES is a way to refer to external information. And METAL lets you define template regions that acts as reusable macros: headers, copyrights, headlines, boxes, what have you. METAL greatly aids in supporting the idea of "skinning". Represent documents as TAL templates that refer to METAL macros, and to switch your "skin", just point them to a different set of macros.

    TAL, which is based on XML, is a declarative language. It will take some time -- but not much -- to get used to. For example, to iterate over a list/array/whatever:

    <tr tal:repeat="person results">
    <td>...</td>
    </tr>

    This goes over the elements in the "results" list, and for each element, assigns the value to the variable "person".

    <tr tal:repeat="person results">
    <td tal:content="person/name">Person's name</td>
    <td tal:content="person/age">Person's age</td>
    </tr>

    Here, we use tal:content to insert the person's details into the table cells. As you can see, TAL uses a path syntax: person/name means the attribute "name" of the variable "person

  6. Time to whore myself: HTML::Template for PHP by self+assembled+struc · · Score: 3, Informative

    If you know perl at all, I've ported HTML::Template into a PHP class. It's about 1/3 of the size as the Sourceforge project that does just that, doesn't invoke the regular expression engine and generates as few objects as possible. This allows it to run A LOT faster than the other HTML::Template engine for PHP.

    You can get it at http://www.robotholocaust.com/scripts/template.php s

    It uses the same Templating syntax and tries to be a close as possible in API as the perl version, but it doesn't handle caching at all. That's coming soon.

    1. Re:Time to whore myself: HTML::Template for PHP by rakanishu · · Score: 2, Informative

      I'll also recommend HTML::Template. Perl, Python, and PHP all have implementations of it. The same template will work in all three of those languages. It's a pretty simple templating syntax that has the option of being embedded in HTML comments.

  7. Re:I like template engines by j|m · · Score: 3, Informative

    My kingdom for some mod points! Templates aren't the solution to most problems in this case; XSLT is!

    It's powerful, extensible, and - best of all - language-agnostic. I've built several sites using the PHP+MySQL->XML->HTML route and I can't say I've found anything that works better.

  8. Re:I like template engines by jrc313 · · Score: 2, Informative

    And, if their browser supports it, you can pass the XML and XSLT to the client and let them do the transformation for you.

  9. Tried Smarty, switched back to raw PHP by Anonymous Coward · · Score: 1, Informative

    My experience: I tried several PHP engines and settled on Smarty at first. My reasoning was 1) the different language creates a conceptual distinction between programming PHP and programming templates; 2) several useful things like select boxes, dates, etc., are present and ready-to-use with easy tags; 3) it's possible to auto-escape all HTML; and 4) it's all converted into PHP anyway so there's little performance hit.

    Then, reality set in..Smarty requires special directories set up to save its cache files, which are owned by the web server user. These would constantly annoy me when developing an app under my own username for later uploading to the web server. And it never cleans out the old ones.

    Smarty's built-in functions are pretty useless once you move beyond what they offer. For instance, I wanted to have "month" and "year" appear at the top of smarty's date select boxes,
    but you can't do that. So new select boxes always show "Jan" "2004" which is bad from a UI point of view. So I ended up writing it in PHP anyway.

    Smarty code screws up syntax highlighting in the editor. Most editors know about PHP tags, but not smarty tags (even ones that claim they understand smarty will still choke on a {php} block for instance).

    It's possible to do "template-driven" coding (where the name of the template is used in the browser URL, rather than a PHP script that loads the template from somewhere), but very awkward. The whole thing is full of design smells.

    Auto-HTML escaping doesn't actually work! There is a flag for it but it is never read by the code anywhere. That one made me laugh out loud. I'm really picky about this because I believe all output should be HTML-escaped by default.

    When you want to do something complex, you have to fall back to {php} blocks. For instance I needed to chunk an array into an array of 5-element arrays, for an online photo gallery type of application. Can't do it in Smarty (afaik).

    Generally smarty's syntax is okay for just variables {$foo} but let's say you want to apply a PHP function, you have to do something like {$foo|@php_func} .. extremely awkward and it doesn't "scale" to complicated expressions. Even HTML escaping is awkward. Accessing loop variables from within a loop is also extremely awkward and non-intuitive.

    So in the end I ditched Smarty completely and went back to regular PHP. My code base is a lot smaller and clearer. My brain understands that this is a template, and not PHP "logic", since I use "<? ?>" tags in the templates, but "<?php ?>" tags elsewhere.

    I eventually came up with some syntactic sugar which makes my templates a little more object-oriented and Smarty-like (i.e., populate the fields of an object, and then include() the template in the scope of the object), and I created a bunch of short-named functions to handle escaping, defaults for variables, select boxes, etc.

    My designers understand it just the same as smarty, and it shows up in dreamweaver with the correct highlighting, etc. I can create helper functions in PHP that are unit-testable and easy to use from the templates. Everybody is happy.

    The only drawback is that it still doesn't auto-escape HTML. But neither did Smarty!!!

    I'm never going back to Smarty .. it's a perfect example of "open source cleverness" if you know what I mean (see also, Subversion). Somebody comes up with a design, perfects it and improves it, others come on board, but nobody ever seems to ask the question, "is this design the right one?" Usually when I need to get work done, I really don't care if it is elegant or not, but Smarty CONSTANTLY got in my way.

    So, I recommend just using plain PHP, and keeping an eye out for any template systems that just set up the variables, and pass them to a PHP file, and that's it. That's the best PHP template system.

    1. Re:Tried Smarty, switched back to raw PHP by profet · · Score: 2, Informative
      For instance, I wanted to have "month" and "year" appear at the top of smarty's date select boxes, but you can't do that.

      You didn't look very hard. check out the "year_empty", "day_empty", and "month_empty" options here.

      When you want to do something complex, you have to fall back to {php} blocks. For instance I needed to chunk an array into an array of 5-element arrays, for an online photo gallery type of application.

      Chances are that what you are doing is hardly presentation logic. And if it was...then it probably could of been accomplished using a combination of Smarty functions like cycle and foreach.

      At this point I stopped reading your comment simply because it was clear that you didn't RTFM and with or without knowing it...you are simply trolling.
  10. View on Smarty by j1ggl3x · · Score: 3, Informative

    I'm a PHP/Smarty user right now (and I haven't really dabbled in the other templating engines), but after separating business logic from presentation, you really can't go back. Regardelss of what template engine you choose to use, having flexibility in the presentation of data, as I've discovered, is a huge convenience. One of the most important uses for me is quickly pumping out RSS feeds, different styles for my users, etc. all from the same business logic. Personally, I really enjoy using Smarty and its been incredibly fast on my servers. That being said, I'll dive into the pros and cons of Smarty and present an alternative that I really like.

    Overhead
    As for the argument about overhead, sure all templating engines do add some amount of overhead, but depending on your server load, power of webservers, etc., the significance of the load may either be infintesimal or enormous. I know that Smarty tries to reduce the load by caching the compiled template files to save some time. Basically, on the first page load, Smarty compiles and caches all the smarty files into PHP files, so in the end, you're basically running a bunch of PHP code.
    Of course, with all business->presentation, there is the overhead of looping through your data set twice: once to retrieve and store the data, and once to display it. However, this is only a constant factor in complexity, so it should not be a significant overhead.

    Flexibility
    Smarty is an extremeley flexible templating language, since you can basically wrap any php function and pass it in as a plugin, thus opening up the entire PHP library through smarty functions. In fact, you can always cheat with Smarty and throw in the {php}{/php} tags, though may add confusion to the design process.
    And this brings up the largest problems with Smarty though (from a PHP programmers perspective), is that you do have to spend time learning a new language. While several of the constructs are similar to PHP, it is different enough to warrant some amounts of frustration. I'm sure this applies to any templating engine as well.

    Alternative to templating "engines"
    Like another poster pointed out, you don't really need a separate templating "engine" to use templates. Templating can be acheived using pure PHP itself, as long as you create the correct classes and strictly enforce keeping all design out of the business logic. (The link gives more details about that).

    Smarty may be a good choice however, if the designers of the company does not have PHP knowledge. Teaching them the small amount of Smarty (the language is very small) may be faster than ramping them up on a PHP template. And Smarty was made for this purpose, a templating language with a SIMPLER function set than PHP. It was created (afiak) keeping in mind that not all those HTML/WYSIWYG designers have expert knowledge of PHP.

  11. Re:Not terribly useful by Anonymous Coward · · Score: 3, Informative

    No trick, just experience. My general approach:

    1. Write plain XHTML 1.0 Strict using appropriate markup.

    2. Write a stylesheet to get the layout right. Avoid the bits that Internet Explorer fucks up, mostly CSS tables and certain types of selector.

    3. Develop against the highest-quality CSS implementation available, usually the most recent Gecko-based browser.

    4. Test in other decent quality browsers (Opera, Safari, Konqueror). Include bug workarounds where necessary.

    5. Test in Internet Explorer 6.0, include bug workarounds where necessary.

    6. Test in Internet Explorer 5.5, include bug workarounds where necessary.

    7. Test in Internet Explorer 5.0, include bug workarounds where necessary.

    8. Go back and check that your bug workarounds haven't broken anything in any of the browsers.

    9. Fine tuning.

    It sounds long-winded, but it's usually only steps 5-7 that take the most time and effort because some of Internet Explorer's bugs are truly incomprehensible (such as text or entire sections of the page randomly disappearing).

    Once you've done this with a few websites, you learn the best approaches and the problem areas to avoid. It's usually better to use floats than absolute positioning, for example.

  12. Re:Template Engines are bad by Fweeky · · Score: 2, Informative

    Using divs everywhere is a really bad idea; if you've got a list of links, make it a UL; if you've got a section heading, use a Hn; if you've got a selection of paragraphs, use P. DIV and it's inline cousin SPAN should be treated as a last resort when some more meaningful and more usefully rendered-by-default tag isn't available, not as your most used element. If your document doesn't stand alone from the CSS without devolving into unformatted drivel, you're doing something wrong.

    And even with CSS, you often end up with little presentation-dependent bits in your markup; be it with document ordering, flicking between class names for a specific style you can't otherwise achieve without fancy selectors IE doesn't support, and so on; having these things seperated out from the main logic of your application is a significant win.