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

90 comments

  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. Re:PHP blows by dingd0ng · · Score: 0, Troll

    Off-topic, I know, but what does "suXors" mean?

    --
    Pay no attention to that man behind the curtain!
  3. 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.

    1. Re:I have mixed emotions by greenhide · · Score: 2, Insightful

      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.

      In my experience, bad programming starts with the developer, not with the language. Languages that are more difficult to code in simply make the barrier to understanding a little higher, so they're *more likely* to be used by someone with good programming skills.

      Remember: The main goal of programming is to ensure that the end result solves the problem presented. Elegant code that doesn't result in what you want is probably worse than slightly ugly looking code that actually works.

      I've encountered plenty of programmers who are skilled at coding, but aren't good at paying attention to the needs of the project, so they spend time on the wrong elements, implement features that aren't needed, and omit features that are needed.

      The advantage of more flexible coding (which is equally possible with ColdFusion as it is with a more complex language) is that it is faster to make changes to the system. If everything was hardcoded or overly-coupled, then changes will be difficult. However, for well coded ColdFusion applications, changes are very, very easy to make -- much easier than a similar implementation in a "real" language.

      I've been coding in ColdFusion for a long time and I won't claim that I've never written bad code, but the language itself allows for applications that are very well written, robust, fast, and easy to update and change.

      Fusebox is the most popular programming methodology for ColdFusion, and they have versions of it for PHP as well now. I'm not sure how well it works with PHP, but I do know that it does a fantastic job with ColdFusion.

      --
      Karma: Chevy Kavalierma.
  4. 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.

  5. 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!

    1. Re:Smarty, Smarty, Smarty by jacqui1811 · · Score: 1

      Smarty is too cumbersome to bother with. It may be powerful but I use patTemplate http://www.php-tools.de/site.php and that has EVERYTHING you could wish for in a templating engine without the extra luggage of smarty.

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

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

    3. Re:I like template engines by lowmagnet · · Score: 1

      This is also true, but it is better to be browser agnostic and code to web standards instead of waiting till you're blue in the face for browsers to support XSLT completely. ;)

      --
      Heute die Welt, morgen das Sonnensystem!
    4. Re:I like template engines by Anonymous Coward · · Score: 0

      hey *retard*, maybe you didn't notice that he said *if the browser supports it* duh.

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

    1. Re:they rock by privatepepper · · Score: 1

      I also wrote my own, simply because I really don't know all the perks oof a pre-written engine. All mine does is open files or read a MySQL table, interpret {VARIABLES} and stuff like that, and print everything into a standard template. Very simple, very quick, and it does the job nicely.

    2. Re:they rock by Mazzie · · Score: 1
      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.)

      I have read more comments like this than I can remember, and it is only partially true.

      Smarty converts the template to pure PHP code the first time it is called, and only parses the raw template if it is modified. There is still overhead to check for modifications, but this can be turned off. Smarty is a monster app, but if you are using a PHP accelerator speed issues become almost moot (in my experience).

      In regards to caching, I don't feel that caching speeds up Smarty at all, if anything it might slow it down a bit if you have 10s of thousands of cached pages. However, I believe that caching was originally meant to greatly reduce the load on your database server, which it doeas a great job of.

      The greatest power of Smarty that gets very little attention is the plugin system which saves just unbelievable amounts of time by dropping in plugins that someone else has already taken the time to write. I also write many of my own plugins for specific tasks which greatly speed up HTML development.

      --
      Having a bookmark to Google does not make you an expert on everything.
  8. Not terribly useful by Anonymous Coward · · Score: 1, Insightful

    I use XHTML 1.0 Strict and CSS extensively, so when it comes down to it, there is very little in the way of markup to abstract away, and a template engine merely gets in the way.

    If you are constantly tripping over nested tables and font elements, perhaps you are solving the wrong problem by trying to rationalise that markup instead of using HTML properly in the first place.

    1. Re:Not terribly useful by m_evanchik · · Score: 1

      I'm not trying to troll, but what's your trick to using CSS and XHTML without coming across lots of browser incompatibility issues?

    2. 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=

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

    4. Re:Not terribly useful by Anonymous Coward · · Score: 0

      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.

      Don't get me wrong, I'm not saying that XHTML and CSS can handle application logic or anything like that, it's just that template engines seem to me to be a response to having to pick around masses of complicated 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.

      Really, why is that necessary? I could understand it if it was a massive multi-layered bunch of tables and font elements, but a couple of <tr>s and <td>s in a loop are dead simple to manage, much more so than trying to abstract it away into a template engine.

    5. Re:Not terribly useful by mkavanagh · · Score: 0

      overboard? phpBB stable's template engine is a fairly minimalistic, baseline templating implementation :) nothing near as complex as smarty or others. :)

    6. Re:Not terribly useful by DeltaSigma · · Score: 1

      You definately have a point. If your entire site (or significant section of your site) contains tabular data (such as a forum) then you obviously should consider a templating system.

      However, the parent also has a very good point. When your markup looks like this:

      <html>

      <head>

      <title>Title</title>

      <link rel="stylesheet" type="text/css" href="layout.css">

      </head>

      <body>

      <div id="nav">

      <?php require("navigation.php") ?>

      </div>

      <div id="con">

      <?php require("content.php") ?>

      </div>

      </body>

      </html>

      (excuse the potential crap php statements, it's been a while, and excuse the non-XHTML compliance, hell just use your imagination)

      When your markup looks like that using a template system is hardly advisable, or even sane.

  9. cost vs benefits by gyratedotorg · · Score: 1

    these days, with computers as fast as they are, id argue that the benefit of maintainability far outweighs the cost of the additional overhead for all but the very largest sites. and most modern template engines have some sort of caching mechanism anyway.

    of course the best test is to run some benchmarks for your specific application, but in general, i dont know why anyone would choose NOT to use a template engine.

    --
    Gyrate Dot Org - "Where high-tech meets low-life"
  10. 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

  11. Useful for applying PHP to a non-php enviroment by m_evanchik · · Score: 1

    I've looked into templates mainly for their cacheing ability.

    I've worked in enviroments that require plain HTML, so I was looking at setting up the logic in PHP and using the template to build it out into a static site. The only problem is that I'm lazy and ignorant ; ) and the thought of learning something on top of the PHP, which I dodn't know too well to begin with, was daunting. Smarty seems to be the most mature platform, but it looks like it requires a fair amount of arcane expertise

    1. Re:Useful for applying PHP to a non-php enviroment by tiptone · · Score: 1

      if figuring out Smarty looks like too much of a daunting task you might consider returning to writing static HTML and not to do anything that is viewed as "programming".

      Smarty is dead simple, go to the documentation page and start working your way through the table of contents. if you don't have a firm grasp of it by section III give up you're not gonna.

      --
      Please don't read my sig.
    2. Re:Useful for applying PHP to a non-php enviroment by m_evanchik · · Score: 1

      Thanks dickwad, that was real helpful.

      "RTFM"

      Is that how you learned to suck on your mom's dick?

    3. Re:Useful for applying PHP to a non-php enviroment by tiptone · · Score: 1

      need help? got a problem? post a question.

      whining about the rather thorough documentation and making crass comments about my mother aren't going to get you anywhere.

      --
      Please don't read my sig.
  12. 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.
  13. 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

    1. Re:TAL by dismayed · · Score: 1

      Very excellent summary of TAL... I'd like to point out one more potential benefit of TAL is that your templates are then portable between implementation languages.

    2. Re:TAL by Anonymous Coward · · Score: 0

      TAL is a horrible, horrible alternative for developing web applications. (For web _sites_ it works just great, though.)

      Only 1 in 10 developers can get their head wrapped around the central concepts neatly enough for them to produce maintainable code on a realistic timeframe. (I'm sure there is no reason why those developers wouldn't learn, if their employer wants to invest their time in it, but this will only happen if that 1 developer happens to be a technical lead who is unable view the things he works with from the perspective of other employees.)

      If you're the 1 developer to whom the concepts come naturally, things are just great. But you are like me in that you manage software developers and projects, I'd advise using some other solution, there are scores of just as good templating systems and web application development frameworks out there that allow better quality work with less investment.

      Why am I qualified to say this? I'm developing a TAL-based Zope application for 50,000 users, and we're almost certainly facing a total rewrite of at least one of the components before 4Q2004.

      We will have to rewrite the Java parts as well, as the product we're developing upon is too complex (and crufty) to be maintained with the currently projected maintenance budget, and we're really only using only one rather trivial part of the product in the end.

      Oh well, ce la changing requirements.

    3. Re:TAL by Earlybird · · Score: 1
      • So what you're saying is, TAL is basically a poorly-documented, not-as-well-researched, not-as-stable version of XSLT?
      I'm not. TAL is well-documented and well-researched, and has different design requirements than XSLT.

      Specifically, XSLT is traditionally applied to static documents. You could apply it to dynamic documents, but how do you generate the document? Not with XSLT. You could generate it with TAL, though, and use XSLT for the presentational transformation.

    4. Re:TAL by Earlybird · · Score: 1
      • Only 1 in 10 developers can get their head wrapped around the central concepts neatly enough for them to produce maintainable code on a realistic timeframe.
      Then I suggest hiring more intelligent developers. Sorry, but TAL/METAL is as simple and straightforward as it gets.

      METAL has its weaknesses (the worst of which is that macros aren't parameterizable), though, leading to some awkward code; I will grant you that.

      Can't see how you can blame TAL for your woes, though.

    5. Re:TAL by Anonymous Coward · · Score: 0

      Dude, you clearly know little to nothing about XSL and XML. The document is XML. How do you get that XML? Millions of ways, most of which do not involve static documents.

      Duh.

  14. 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 Anonymous Coward · · Score: 0

      wrong... what happens when someone asks you to change the design of the page.. you are chopping up your html/php code.. when you could only change the html.

      what happens when you want to add non-html support.. you have to create all new scripts / html / php code... blah...

      when you could have just created a new templates ontop of your current system.. for anything with anyuse you should use templates.

    2. Re:Template Engines are bad by jamienk · · Score: 1

      > what happens when someone asks you to change the design of the page

      You change the stylesheet. CSS is not trivial. You can control things BETTER than if you change HTML with formatting.

      >what happens when you want to add non-html support

      If you are using a template system, you could just change the template. With my system, you'd need to change the PHP. BUT, with my system, you could just make alternate stylesheets to make the page good for PDAs or for print, etc.

      Also, my system could arguably be ported to another programming language with HTML output more easily than yours. I'd just have to re-write the logic/structure document to output the same divs. But you'd need to create an entire structure to support your templating system.

      >for anything with anyuse you should use templates.

      PHP templates separate logic from structure. HTML + CSS separates structure from presentation.

    3. Re:Template Engines are bad by Grotus · · Score: 1
      PHP templates separate logic from structure. HTML + CSS separates structure from presentation.

      Why not do both? PHP templates for the structure, CSS for the presentation. Nothing about templates says that you have to do the styling in them.
      --
      "From my cold, dead hands you damn, dirty apes!" - CH
    4. 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.

    5. Re:Template Engines are bad by Anonymous Coward · · Score: 0

      what happens when someone asks you to change the design of the page.. you are chopping up your html/php code

      Chopping up HTML interspersed with echo($foo)s is no different to chopping up HTML interspersed with {FOO}s.

      what happens when you want to add non-html support.. you have to create all new scripts / html / php code

      You don't have to create your whole PHP application again, unless you have mixed control logic with the output script. Creating "all new scripts" for the new format that are simply a bunch of HTML files with echo statements is just as easy as creating all new templates for the new format.

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

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

    2. Re:Time to whore myself: HTML::Template for PHP by shrubya · · Score: 1
      1/3 of the size as the Sourceforge project that does just that

      Why don't you work together with the htmltmpl folks?

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

    1. Re:Just a rule set? by Alpha27 · · Score: 1

      I don't think you are missing any points.

      I've thought of this as well, why go to something else that will emulate a language, when you can use the language itself.

      I think part of the reason why people don't see the point is that we automatically think of using a template engine first, when we do think of one, and just accept the inherent design of one. I believe current engines are emulating previous ones, and therefore have carried over what they have learned from the old ones into the newer ones used today.

  17. PHP is ITSELF a templating language by dozer · · Score: 2, Interesting

    I have yet to see a PHP templating engine that can do more than PHP itself. Variables, tag substitution, subfiles, looping... It's all in there at extremely low overhead. You just have to use PHP the same way you'd use the templating engine (separate business logic and content, etc).

    Can anybody explain what any of these templating engines gives you that can't be found in PHP natively?

    1. Re:PHP is ITSELF a templating language by cybermage · · Score: 1

      Can anybody explain what any of these templating engines gives you that can't be found in PHP natively?

      I cannot speak to most of the template engines being discussed; but, as far as fastTemplates goes, here's the difference I see:

      fastTemplates is just another PHP class that is prewritten to handle the concept of templates. The chief advantage I've seen in using it is that you can write pure HTML (or for that matter a non-programming designer type can) and then you place tags (formatted like {TAG}) where you want your dynamic elements to go. A page request hits your PHP, you map the request to a master template, execute business logic to determine what data (including sub templates) will replace the {TAGS} and then call the fastTemplates print method to send the composited page to the browser.

      If you were to think of your PHP application using the MVC architecture, the Controller php script deals with Model php scripts and tells the View template engine what to render. When the Controller script is done, it calls the View template engines print method and it assembles the content for the browser and sends it.

      The chief advantages are in encapsulation. With care, you can seperate the design from the code; and, contrary to another poster, that design can use CSS. It's just HTML with some extra tags as place holders for subtemplates and other data.

    2. Re:PHP is ITSELF a templating language by Anonymous Coward · · Score: 0

      you can write pure HTML (or for that matter a non-programming designer type can) and then you place tags (formatted like {TAG}) where you want your dynamic elements to go.

      How is that an advantage to placing <?php echo($foo); ?> where you want your data to go?

      A page request hits your PHP, you map the request to a master template, execute business logic to determine what data (including sub templates) will replace the {TAGS} and then call the fastTemplates print method to send the composited page to the browser.

      Sounds like a lot of trouble compared with a simple echo statement.

      The chief advantages are in encapsulation. With care, you can seperate the design from the code; and, contrary to another poster, that design can use CSS.

      If you are referring to my other post where I said that CSS dramatically reduced the need for template engines, then you completely misinterpreted what I was saying.

      It's just HTML with some extra tags as place holders for subtemplates and other data.

      So again, how is this better than "just HTML with some extra PHP echo statements"?

    3. Re:PHP is ITSELF a templating language by Anonymous Coward · · Score: 0

      I have yet to see a PHP templating engine that can do more than PHP itself.

      Sure. And I've yet to see a high-level language that can do more than assembly code. I'm not joking. It's true. So why do I code in Python? Because each line of code I write in a higher-level tool does more than the underlying primitives I'd have to string together, and it does so in a way that's been well-tested for reliability, security, etc.

      In other words, as long as it saves me time and lets me focus on more valuable tasks, I'll use a high-level tool. Assuming it has some degree of maturity and has proven to not be a security liability.

      PHP provides the primitives. Template libraries use PHP syntax (obviously) but wrap things up into bigger bang-per-function-call than PHP's native primitives.

      This all assumes that the need the template provider saw was a need that matches yours. If yours is an unusual case, then by all means get rid of the fat template libraries and craft your own PHP code. And maintain it. And debug it. And audit it for security exploits. And... :-)

    4. Re:PHP is ITSELF a templating language by dozer · · Score: 1

      So you can use {TAG} instead of <% $TAG %>. True, that _is_ nicer, but I'm not sure it justifies a whole new language. Everything else you said (organizing the project as MVC, encapsulation, separate business logic, static templates) can be applied to PHP itself just as easily as it can be applied to any templating system.

      What am I missing here?

    5. Re:PHP is ITSELF a templating language by cybermage · · Score: 1

      How is that an advantage to placing where you want your data to go?

      Your designer has to know about variable $foo, for one thing.

      Sounds like a lot of trouble compared with a simple echo statement.

      I guess that depends on the scale of your project. If you're doing something really big, or even moderately big, seperating presentation from business logic is a really big deal.

      If you are referring to my other post where I said that CSS dramatically reduced the need for template engines, then you completely misinterpreted what I was saying.

      I was referring to a post where someone implied that CSS and templates where mutually exclusive endeavors.

    6. Re:PHP is ITSELF a templating language by cybermage · · Score: 1

      What am I missing here?

      In my experience, templating systems in PHP are just classes that are already written to save you the trouble of writing them yourself. Templating is really a matter of creating an object of that class at the beginning of handling a request and then handing the object the elements that you want presented as your program naturally flows. When you're done executing, you tell the object to print itself. This way, your code doesn't need to be aware of the HTML.

    7. Re:PHP is ITSELF a templating language by Anonymous Coward · · Score: 0

      Your designer has to know about variable $foo, for one thing.

      What, so the designer just magically knows about {FOO} but doesn't magically know about $foo? Come off it, you are applying a double standard.

      If you're doing something really big, or even moderately big, seperating presentation from business logic is a really big deal.

      I agree 100%. But I never said otherwise. I was asking what the benefit to using templates was. I already know about the benefit of separating presentation from business logic and have been doing just that for years. You don't need templates to do this, you can do it with plain PHP.

    8. Re:PHP is ITSELF a templating language by Mr.+Slippery · · Score: 1
      The chief advantage I've seen in using it is that you can write pure HTML (or for that matter a non-programming designer type can) and then you place tags (formatted like {TAG}) where you want your dynamic elements to go.

      That description applies to PHP itself, except that the tags are formatted like <?php ... ?>.

      Seems to be that the template engines are a just simplified/dumbed down (pick your bias) version of the same idea.

      I don't see much use for them; I keep my application and database logic in separate classes or functions, and my main PHP scripts are pretty simple. I'm trying to move more towards CSS, too.

      (The legacy code I'm dealing with is CGI programs, written in poorly organized C/C++. Not FastCGI, but good old fork-me-all-day-long CGI. They output font-tag riddled HTML. Oh, and the data is in flat files and gdbm files. So just getting things like PHP and PostgreSQL in the door has been a challenge; I'll save cleaning up the resulting HTML to use CSS for later.)

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
  18. 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.

  19. My Two Penneth by polyp2000 · · Score: 1

    I've been doing PHP for some time. There comes a time as with other server site scripting languages e.g ASP or JSP, when trying to maintain two different types of script (HTML and PHP) mixed within the same page becomes an irritation. I found myself implementing my own templating engine without really realising there were alternatives such as smarty and the like out there. Just to try and avoid mixing too much html and php within the same page.

    It does make a lot of sense if you are doing sites that require more than just an email submit form etc. But it is probably an un-neccesary over head for a small site thats rarely updated. Like many questions asked on slashdot the answer really depends on the situation. A side effect of templating your site in this way it gives you a lot more power in the way you display sort and categorise content.

    --
    Electronic Music Made Using Linux http://soundcloud.com/polyp
  20. theme engine versus template engine by ubiquitin · · Score: 1

    Although there are differences between templating and theming, PHPWebSite, Geeklog, and the Nuke-a-likes all provide functionalities that can loosely be described as a template system. Although this might seem off-topic at first glance, if you take a look at how the themes in geeklog and phpwebsite work, you might be suprised at how similar they are, in concept, to smarty (think square brackets versus curly braces). So these links are intended to give someone who is looking into html presentation-layer manipulation a more complete idea about the options out there.

    --
    http://tinyurl.com/4ny52
  21. You know what I think... by borius · · Score: 1

    I think there are way too many business types on Slashdot who spout buzzwords like "business logic" and "n-tier model". Where are all the old-school hacker guys? All I read about these days is making robust code that has lots of maintainability and other boring stuff like that... Is hacking dirty? Only if you do it right :)

    Heh, flamesuit on :)

  22. 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.
    2. Re:Tried Smarty, switched back to raw PHP by ctxspy · · Score: 1

      Well said.. i wish i had mod points :(

      I also use smarty on a daily basis, and I think the grandparent's post is terribly misleading.

      His rant reminds me of people that claim the Atkins diet doesn't work. 9 times out of 10, they are woefully misinformed, underinformed, or just malicious.

      This guy should've asked around on how to do things instead of just assuming that if it wasn't immediately obvious, it wasn't possible.

    3. Re:Tried Smarty, switched back to raw PHP by Anonymous Coward · · Score: 0

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

      That was added in Smarty 2.6.1, just recently. Not very useful when you have a deadline to meet a year ago. Now let's see, how do I add a blank entry in between the first element and the other elements? What if I want to add "any month" at the end of the months, separated by another blank line? It's a wall, waiting to be hit.

      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.

      Dividing an array into a grid for display is definitely display logic. Yeah, you can accomplish it using Smarty's awkward loops, but PHP already has a function to divide an array into "chunks", why can't I just use that? It's a *lot* clearer an less error-prone just to call this function on the array, then run two foreach loops.

      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.

      Hey, I wanted to like Smarty, but it just didn't work for me. If it works for you, fine. Folks just need to realize, PHP is *already* a template system, and Smarty doesn't live up to the hype once you get past simple sites.

    4. Re:Tried Smarty, switched back to raw PHP by profet · · Score: 1
      That was added in Smarty 2.6.1, just recently. Not very useful when you have a deadline to meet a year ago.

      Your original quote was:
      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.

      Maybe you meant "couldn't" but you said "can't." So I replied with that in mind.

      Now let's see, how do I add a blank entry in between the first element and the other elements? What if I want to add "any month" at the end of the months, separated by another blank line? It's a wall, waiting to be hit.

      I think you are losing site of the goal here. The date/time tags are for quick and dirty drop downs. If you want to do all this custom work, then just write your own option tags. It's not a wall. It's you being short sited.

      Dividing an array into a grid for display is definitely display logic. Yeah, you can accomplish it using Smarty's awkward loops, but PHP already has a function to divide an array into "chunks", why can't I just use that? It's a *lot* clearer an less error-prone just to call this function on the array, then run two foreach loops.

      What you call awkward, I call different. And there is nothing wrong with different. I like being able to point my template designers to the 50 pages or so of smarty documentation rather than the thousands of pages of PHP documentation and OO theory needed to read/edit my projects.
  23. They are the key to programming success. by madstork2000 · · Score: 2, Interesting

    I have been working on my own templating system / toolkit for quite a while. I use a central wrapper, and include "handlers" parse and handle various other PHP and non php data sources. Using this approach I can integrate other systems and seamlessly tie NUKE, PHPBB , PHPSHOP and other common php applications all with my own template engine.

    My main purpose is to design interactive applications or "admin sites". I have code templates (seperate from the layout templates). That enable me to generate an decent looking application, with the ability to add/update/delete/browse/copy/update multiple records based on a mysql table in under an hour. I have code that builds a config file based on the database schema, and provides basic data validation for things like phone numbers, credit cards, date ranges, zip codes, etc. So when customers approach me with custom application requests 85-90% of the coding is done.

    A side benifit for this is the business logic can be seperated from the infra-structure and templating logic, so the site are easily maintainable (and upgradable, since my template handler scripts, can be swappped out and upgraded). This also helps security, because I will disable certian handlers, based on the authenication level, and can store the handler scritps outside the web directory tree, so if you don't have the proper rights the file handler simply does not exist, or a lesser version of it does.

    Another important benifit is that this extra layer of seperation, and pre-coded templates help me maintain a very consistent look across the various admin screen with very little effort (the html forms are automatically generated based on the DB schema, and the user defined config file). That way if you add a field to the database, it instantly appears in your application, no need to update HTML/PHP code, its all done automatically.

    The vast majority of the core application is written and maintained by me. I distribute it to my clients under the GPL, but I have not formally released the application other than to people who are using it.

    They can be slow, and cumbersome if they are too database dependent, but because the logic and data and layout are all well organized it is very easy to automatically create static pages if need be. (This is another feature of my toolset, albeit an incomplete one).

    Anyway, without the structure of a templating system I would not be able to stay in business. I don't believe in plugging my business on slashdot. But, if you are really interested in knowing more you should be able to track me down via my slashdot info. Ask for Brandon :)

    -MS2k

  24. "The HTML template class" by xFallenAngel · · Score: 1
    I have been using this simple template library.
    It is basicly nothing else than using php control structures,
    but it keeps my html code clean (if you can call html clean).
    Its not at all bloated and suits my need for page load.

    I'd say its worth a try :)

  25. Bah by Anonymous Coward · · Score: 0

    Real men use Java/Struts/JSTL.

    And we get paid like real men, too.

  26. Just curious by gtrubetskoy · · Score: 2, Interesting

    Isn't PHP essantially a template engine in itself? What's the rationale for using a template engine from within a template engine?

  27. You'll like this. by colinramsay · · Score: 1

    ASP.net has something called user controls. These use custom tags combined with controlling code to make for an incredibly easy basic separation of presentation from content.

    I learned PHP to a moderate level, and now ASP.net to a moderate level, and ASP.net is the first language I have ever felt is truly for the web.

    It's not perfect, no. And yes it's Microsoft. But C# is an open spec don't you know. And if MS was ever going to redeem itself, it had to start somewhere. ASP.net on the web is part of that.

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

  29. HTML_Template_IT and templating in general by h3 · · Score: 1

    I've been using PEAR's HTML_Template_IT, which has been included in the default PHP distribution for some time. I looked at Smarty as well, at the time I investigated templates, and decided it was overkill for what I wanted.

    After a couple of years now, I must say that I *hate* HTML_Template_IT, on a number of levels. Debugging problems is the crap because it fails silently for the most part and I'm left do a lot of manual tracing. Furthermore, it doesn't behave the way I think it should a lot of time, doing replacements where I don't think it should, etc.

    On a general templating level, I get irritated sometime with tracking down problems. Is it in the primary PHP file? The template? The CSS? Where is it?!?! It's the nature of the beast, I guess, but as I work solo for all my projects, I know I've lost a lot of accrued time just hunting the problem down to the right file.

    I happened to do some benchmarking recently, with ApacheBench, on a new server I'd just rolled out. Apache was dishing out static pages at about 2500/sec. Regular (non-templated) PHP pages doing simple stuff (includes, mostly) were churning out around 300/sec. My template projects: 25/sec. Luckily, this is low-traffic stuff.

    I still use it, though. Inertia, I guess. I have to maintain those projects so I have to keep using it regardless. I don't mean this to be a screed against the HTML_Template_IT folks, or templating in general. In fact, I'm resigned to it as the thought of going back to HTML interspersed in my PHP horrifies me. But it's not all roses.

  30. PEAR::HTML_Template_Sigma by TekZen · · Score: 1

    I use HTML_Template_Sigma. It has a similar API to HTML_Template_IT, but more flexibility and some really important extra methods (hideBlock). I don't like templating systems that allow you to place php code into the template (Smarty). This just encourages bad bahaviour. I want to be able to have the entire set of template files over to a designer and let them make all the changes they want. HTML_Template_Sigma has been great for that.

  31. I've written a few... by Fweeky · · Score: 1

    The last being SimpleTemplate; this actually reminds me that I really should do a 2.1 release...

    Anyway, it's simple, compiles templates to php, and generates fairly nice code. If Smarty's a bit heavyweight for you, it might be worth a look.

  32. Rasmus Says: PHP by booch · · Score: 1

    Rasmus (the original author of PHP) says that PHP doesn't need a template engine, because it is a template engine. There's nothing stopping you from separating your logic in one PHP file and your presentation in a separate PHP file. The logic PHP file would be all PHP code, and the presentation PHP file would be mostly HTML with a bit of PHP code sprinkled in where necessary. The only thing about PHP is that it doesn't require you to separate your code from your logic.

    --
    Software sucks. Open Source sucks less.
  33. The Template View by harry_f · · Score: 2, Interesting

    The notion of templating in PHP (or any web platform) is described by Martin Fowler in Patterns of Enterprise Application Architecture as the Template View.

    Implementation of the Template View is examined in some detail at http://wact.sf.net/index.php/TemplateView, which begins looking at "Why use templates" then examines different styles of templating, in terms of their markup and the API they provide to populate the template with data. The purpose is to lay this discussion to rest once and for all.

    Where PHP's concerned, the real question is why has everyone (and their dog) written their own template engine? In an ad hoc survey we counted over 80 public domain template enignes "out there"

    What's even more puzzling is why 90% of them all look the same with markup like;

    {if $font="bold"} Hello World! {else} Hello World! {endif}

    ...and a pinhole API like;

    $tpl->set('font','bold');

    My guess at the reason why is public here

    .

    As to what template engines in PHP are actually worth using, there are only two IMO;

    The first is PHP itself - use some self discipline and keep the pages where code gets mixed with HTML to the most basic PHP syntax - just the flow control statements like if/else, while and foreach.

    The second is any which can offer templating capabilities similar to Java's JSTL or ASP.NET. Which is where WACT comes in. Check the examples to get the idea.

  34. My choice is Smarty by who+stole+my+nick+Ju · · Score: 1

    I would not use PHP if there was not Smarty.

  35. Am I slow? by pauldy · · Score: 1

    PHP is a template engine. The great thing about it is that it does not force you into that paradigm. However, if you want to separate business logic and presentation simply follow the flow of parsing input, check for errors && Display errors || (setting up output variables, displaying the HTML).

    Due to the nature of the web I have yet to see even a single page were I wanted to force data out before processing was complete. I understand the idea of sending data to the client before it is complete seems attractive because it shows responsiveness but in practice I have never seen it make a difference.

  36. I wrote my own by DrSkwid · · Score: 1


    with simple @keword substitution

    as for performance hit : zero, nada, zip

    Because I cache the output of my pages and the forms I use for editing the database entries clears the cache as necessary so I can write my php as un-optimized as I like which places the optimium time saving where it counts - developer time.

    --
    There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter
  37. I dislike them by Vertice123 · · Score: 1

    I have come over to the school of thinking that template engines are unneccesary, as php is it's own bestest fastest most robust templating engine.

    Once you realise that a) suitably complex templates will require some form of presentation logic and b) implementing said logic in a template language is completely unneccesary overhead.

    The only exception i will make to this is phptal (http://phptal.sourceforge.net) , which is a php implementation of zope page templates.

    All tal templates are 100% well formed xml documents, and a namespace is used for the templating functions. ie
    <span tal:replace="page.header">placekeeper</span>

    when they are interpreted .. the entire tag is replaced.

    This has the effect of making the template actually BE the static html created by your designer.

    The biggest problem with phptal however is performance, as php4 doesnt make good enough use of object orientation to make it beneficial yet.

    The author is going to reimplement it for php5 though, so it will most likely be my standard templating engine in a few years

    --
    Morals.. isn't that some fancy kind of mushroom
  38. templating in php... by gabe · · Score: 1

    smarty + turck mmcache = fast templating

    --
    Gabriel Ricard
  39. php's built-in template engine by Diclophis · · Score: 1

    sprintf: http://us3.php.net/sprintf

    example in use...

    /* define the functions args... then for each loop in the function define an outer and inner format string */
    function something($arg, $outer1, $inner1) {
    //stupid loop
    for ($i=0; $i<10; $i++) {
    $innerLoop .= sprintf($inner1, strrev($arg), $i);
    }

    return sprintf($outer1, $innerLoop);
    }

    echo something('cheese', '<ul>%1$s</ul>', '<li class=%2$d>%1$s</li>');

    Now you can put whatever you want for the format strings... and the html is never inside anyfunction... its only passed TO the function

  40. Try changing someone else's Templates! by iffer · · Score: 1

    I recently had to customise an ecommerce site (XCART - uses PHP/Smarty templtes) to fit into an existing website. I knew very little about PHP templates, although i am proficient in PHP and just jumped in at the deep end. As a result I found it very difficult to change the structure of the ecommerce site.
    I found that because one template will use another template which will use another template and so on, that the resulting html might have been taken from up to 20 different template files. I found myself searching through file after file to figure out where the output was coming from. This makes it very difficult to make changes to the site if you are not the original author or there is no documentation as was the case with me. I much prefer using PHP on its own.

    1. Re:Try changing someone else's Templates! by benj_e · · Score: 1

      I've done 5 x-cart sites, and frankly it's a piece of cake. Totally changing the look of the site is very simple. It probably would have been better for you to take some time and learn smarty and the x-cart directory structure.

      There are some really amazing x-cart sites out there btw.

      --
      The Tao that can be spoken is not the one eternal Tao
  41. The Way of Smarty by H20 · · Score: 1

    I must say that I'm quite disappointed with the quality of many of the posts that have been made thus far. Many users seem to have missed the initial point of templating and the many advantages offered by using a solid template engine over inline PHP/HTML 'soup'.

    First, a templating engine enforces a set of rules that makes it easier to separate your business and presentation logic because you think of your PHP as code and your templates as presentation. Secondly, the level of reusability goes way up with a proper engine. As an experiences Smarty user, I now have an arsenal of generic modifiers, functions, and blocks that make generating output pages very easily and they can be shared quickly via the Smarty forums (sure you can share functions, but the naming convention and unform behavior of Smarty allows for higher simplicity). Thirdly, template engines offer shorthand {} instead of and insulate your from pulling in global variables and such in the output pages, producing much cleaner and accessible presentation templates. Lastly, Smarty is developed by a dedicated team that made templating their 'deal' and it frees your hands to concentrate on the real work -- the development of your application.

    As to the performance question, if you feel that you should do everything via raw PHP output pages for the sake of speed you are being very shortsited. Performance hits can be mediated by using an accelerator such as Turck MMCache or the Zend Optimizer -- if you are running a production site you should definitely augment PHP with a bytecode cache. Secondly, Smarty can be configured to generate pages via the flexible built-in caching mechanism much faster than your pages -- unless you like reinventing the wheel on this front too. Once Smarty has compiled your template and follows your caching strategy, you are running pure PHP on as many pages as possible, according to the design of your cache.

    - Blake

    --
    Blake
  42. Double your file changes, baby... by kale77in · · Score: 1

    The guys (above) questioning whether PHP needs a separate templating engine are right on the money.

    Like every man and his dog, I wrote my own a year or two back (I think half the appeal of templates comes from the fun they are to write, which then raises the problem of finding a use for them), and I've used Smarty (for a project which was using Xoops), plus a few of the smaller systems.

    In my view simple PHP is (1) just as fast and easy to maintain, (2) more flexible by far, (3) a more portable skill than HTML drone-work, (4) an educational experience (it's not like programming is some kind of black art anymore; designers need to know it to get anywhere in the industry), and (5) a consistently *fast* development solution. Templating is a way of coding, not a level of abstraction.

    To make my point more concrete: Most of my day-to-day code looks a lot like this:

    $result = $db->query("SELECT * FROM table WHERE some_condition=1 ORDER BY something DESC;");
    $nr = count($result);
    if ($nr > 0) {
    ....echo "<ul>\n";
    ....foreach ($result as $row) {
    ........stripslashes_from_array($row);
    ........echo "<li>".ucwords($row['title'])."</li>\n";
    ....}
    ....echo "</ul>\n";
    }

    Now obviously, I can make big HTML blocks and add the vars with <?= $var ?> if I feel something approaching template layout is helpful at some stage. But whether I do or not, the simple PHP is strong and sparse, and most importantly, it's in ONE FILE.

    The fundamental templating mistake is that it's somehow elegant to have to find and change two or more files for every single functional alteration you ever have to make to a script. Such separation decreases code comprehensibility (and so, maintainability) on the PHP side, by removing its best documentation mechanism (it's HTML, whether internationalized or not). I've seen nothing in templating that can improve on the above kind of coding for speed of deployment and ease of maintainability.

    And for my time (and money and satisfaction), that's what this language is really all about.

  43. Custom answers by dave420 · · Score: 1
    After using PHP since '99, and last year I thought it was about time for me to make my own templating toolkit. I came up with a great class I use in pretty much everything I do now. I use it for creating anything from arrays of data (which, as it happens, fits in nicely with my database class).

    Depending on the logic the templating engine understands, you can make excellent websites with tight HTML in minutes.

    The overheads are always present, but it's easy enough to write your own caching methods should you need them. I run a production website at work using the engine, and it serves up massive HTML pages for the sales consultants through my engine, and the performance is great (especially seeing as it's running on my spare computer under my desk :-P)

    I guess what I'm saying is, it's not intrinsically a good or bad thing, as it can be misused beyond belief. If you choose the right solution for your problem, weighing up the pros and cons of it all, it's definitely an approach that can work wonders for most websites...