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?"

16 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. I have mixed emotions by Gestahl · · Score: 3, Interesting

    There are really two things to consider when using template languages like PHP and ColdFusion:

    1) Is the rapid development style worth the processing overhead and system-independence?

    2) Are you prepared to take the extra time to make the code clean after said rapid development?

    Granted, any language can be misused to create horrible code, but with rapid development with template languages, you have to be careful not to let the ease and simplicity of the language lull you into poor programming. However, you do not need to use extra "stuff" to accomplish this specifically, if you are careful to code your data access modules separate from the presentation logic in the first place, which is just good programming style in general.

  3. Smarty, Smarty, Smarty by mog · · Score: 5, Interesting

    I am currently just two weeks away from going live with a large web application written in PHP using Smarty. I can't speak to performance, as it is a complex application with a low number of clients, but for my needs it has been very acceptable. As far as the interface and syntax, I am in love with Smarty. I had become disenchanted with PHP due to the spaghetti code when you don't use such an engine. Smarty .. mmm, it has brought me back. In fact, I'm writing a templating engine for Ruby based on the Smarty syntax.

    Smarty -- highly recommended!

  4. I like template engines by lowmagnet · · Score: 5, Interesting

    I have a template engine based on standards. It's called XSLT, and it's built into the most recent PHP versions. Especially nice is the 5.x branch, since it has been completely rebuilt for speed and compatibility to libxml2. I have a site full of XML, and I transform it with a central XSL template file into the displayed content. It's a shallow learning curve, and I can change the entire site's layout by a few XSL tweaks. For me, it is the perfect solution.

    --
    Heute die Welt, morgen das Sonnensystem!
    1. 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.

  5. they rock by AllMightyPaul · · Score: 4, Interesting

    Ok, so I'm a little biased having written my my own template engine. However, they have their plusses and minusses.

    On the positive side, it really helps separate code from display, which makes everything look neater -- as in clean, not as in "gee whiz". HTML is easier to read and it's easier to abstract everything. I'm sure you know the arguments for it already. If you need to change something, all you do is find the template and you can see everything in one clear shot, instead of digging through mountains of PHP logic.

    Additionally, if you use a good template engine, it will make your pages load faster by using a caching system. Basically, if your page doesn't change very often, it will save a static copy of all of your PHP logic and return that to the browser instead of making the database calls and other operations that eat up processing speed. I did notice a difference when I wrote my site.

    However! There are some important things to remember. Unless you cache your site, it will probably not be any faster. Smarty is, in my opinion, bloated and slow. It tries to do too much and takes forever to load and use. (By forever, I mean like 0.1 seconds to load a page created by Smarty versus 0.005 seconds to load the equivalent page from pure PHP.)

    Moreover, websites made with templates are summarily locked into that template engine and new developers will have difficulty figuring out what the heck you did without a good bit of explanation.

    One more point to consider is the fact that when using template engines, usually you're limited in the tricks you can pull on your website. Template engines seriously restrict your ability to do cool things with PHP in the display process.

    Finally, template engines introduce new flaws into your website. Sometimes those flaws are really bad and affect the performance of your site and then the developers are sometimes difficult to work with and then you have this piece of code that you didn't write that you have to work around.

    Those are just things to consider.

  6. 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.
  7. Re:Not terribly useful by Smidge204 · · Score: 3, Insightful

    It depends on your application.

    For example, a template engine is used in phpBB (as with many message board systems). There's a lot of very dynamic and conditional content on message boards, and I honestly can't see how XHTML and CSS can effectively handle it.

    By abstracting the markup from the data, you can also simplify the markup. For example, if you are generating a table with an unknown number of rows, you can define a single row in your template and the engine will duplicate it as required. Same thing if you even have multiple tables of multiple rows.

    Personally, I think phpBB's engine is a little overboard, but it's like that to be more flexible than the boards I maintain require. For example, I don't see the need to a separate language file for anything I do (although I understand it's usefulness). Similarly, I don't really care for the style table it generates in code from the database (although this makes changing the styles easier via web interface). So to save overhead I remove these features and just put the data directly into the templates.

    What I'm really getting at is: Use the right tool for the job. PHP Template engines are a Good Thing(tm) but definately not the Only Thing(tm)
    =Smidge=

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

  9. Template Engines are bad by jamienk · · Score: 3, Interesting

    I write php and for any relevantly grouped output, I surround it in html div tags. I use a lot of div tags. E.g., to deal with a list of links with descriptions, the entire list is enclosed in a div, each link plus it's description has it's own div, each link has it's own div, and each description has it's own div.

    I keep a list of the classes/ids of the divs. I heavily organize the code so that every element can easily be referred to by a class or id according to a heavily commented list of selectors.

    The PHP file is all structure/programming logic. I put all content in some sort of database.

    Then I write cascading style sheets. You'd be amazed at how many different ways you can make the page look. And not just different colors/font sizes; you can make a sidebar float left or right, or be across the top; you can make links' subsections unfold, or stay invisible until you're in that section; in short, you can make the page be layed-out however you want.

    (A few caveats: I've found, in making the css cross-browser compatible, that sometimes you need to do a few work-arounds that pollute the structured PHP document, things like: make a extra div around a div; maybe use a conditional statement to show an INPUT or a BUTTON tag. But you usually need to pollute your non-css HTML anyway if you want to do some sort of tricky design that is cross-browser compatibile and that degrades gracefully.)

    For me, a separate PHP template engine means that the template itself will be polluted: you'll have HTML that's trying to do design, instead of just describing the page's structure. And of course, the template page will need some programming logic like loops and conditionals.

    Better for your designers learn css than make them deal with some half-assed half-HTML, half-PHP template.

    1) With PHP templates
    --
    * programming logic in php files
    * content in a database
    * structure/design in template

    2) With no templates but using css
    --
    * programming logic & document structure in PHP files
    * content in database
    * design in css

    Two is cleaner, no?

    1. Re:Template Engines are bad by Fletch · · Score: 3, Insightful
      Better for your designers learn css than make them deal with some half-assed half-HTML, half-PHP template.

      1) With PHP templates
      --
      * programming logic in php files
      * content in a database
      * structure/design in template

      2) With no templates but using css
      --
      * programming logic & document structure in PHP files
      * content in database
      * design in css

      Two is cleaner, no?

      No, not really. I mean, from which end? Your .php files sure aren't going to be cleaner.

      Frankly, I think you're missing the point. CSS and templating are not mutually exclusive. Just as CSS helps us separate style from content, so does templating help us remove content from application logic.

      3) With templates and CSS

      • application logic in .php
      • document structure in .tpl
      • style in .css

      I prefer #3.

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

  11. Just a rule set? by eddy+the+lip · · Score: 3, Insightful

    Given the apparent popularity of templating systems for PHP I'm likely in a minority, but I really don't see the point. Languages like perl need some way of getting variables and at least some basic controls structures into the HTML so you don't have to resort to multiple print statements (god, the bad old days...). But PHP does this all on it's own already.

    Granted, this is often horribly, horribly abused with all kinds of spaghetti code strewn about the presentation layer, but this is the developer's fault, not that of the language. There's absolutely no reason you can't implement an MVC architecture (or just put your main code somewhere other than your presentation layer) without resorting to a templating engine.

    As far as I can tell, the only benefit of PHP templates is that it forces you to keep your code somewhere other than in the presentation. This is offset by generally having the ability to drop out into PHP anywhere you want to in the template anyway. In exchange, you add another layer of complexity to your application, increase execution time, are forced to learn a new syntax and are (frequently) shoehorned into the way the template engine thinks you should structure things.

    It's also often mentioned that it's easier on non-coders if you're handing the templates off to someone else for markup. But I really don't understand why (excuse the lack of indintenting - slashdot didn't like it)

    {if $user == "admin" }
    You can {$admin_option}
    {/if}
    is considered more intuitive than:
    <?php
    if ($user_type == "admin") :
    ?>

    You can <?= $admin_option =>

    <?php
    endif;
    ?>

    And if you're going to expose your HTML people to a tiny bit of code, it might as well be the actual language, which they may find useful someday. (Yeah, there's a couple more lines in the PHP example to suit my own formatting tastes).

    It seems to me that their only real purpose is to help enforce some kind of coding standards. I prefer to excercise a little discipline on my own. Nothing but variable expansion and control structures go into the presentation layer. The code that does the real work is elsewhere. If I'm overseeing others, I make sure they do the same. And god help them if they use a print statement for anything besides debugging.

    (Caching comes up as an advantage on occasion, but there are other options that don't involve marrying yourself to a template engine).

    I'll grant that I might be missing something obvious and wonderful. If I am, this is the place it'll be pointed out...

    --

    This is the voice of World Control. I bring you Peace.

  12. This has been discussed in detail already by akweboa164 · · Score: 3, Interesting

    Check out the SitePoint forums for Advanced PHP. The pro's and con's of template engines have been discussed over there in length and it is just a great resource for advanced PHP topics. SitePoint Forums.

    Also, take a look at Harry Fuecks website PhpPatterns. He also has detailed information about PHP templating and the theory behind the code.

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

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