Zend Certified Engineer

phpguru.org

Free PHP, Javascript and C# code

Templating, the correct way

Forget templating engines. They're history. They're slow, they over-complicate things, they don't give you any real benfits over this method, and occassionally, just occassionally, they steal lollipops from small children.

So what is this new method of templating I hear you ask? Well, it's really simple, it's been around since PHP 3.0, and it's built into every single installation of PHP. I introduce you to... the mighty include() function, and the traffic stopping alternative syntax for control structures.

Consider the following sample template code (taken from the template engine you can download on the left):

<INCLUDE FILENAME="header.html">

<IF NAME="if_var">
<table>
        <LOOP NAME="table_rows">
        <TR>
                <TD BGCOLOR="#DDDDDD">{column_1}</TD>
                <TD BGCOLOR="#DDDDDD">{column_2}</TD>
                <TD BGCOLOR="#DDDDDD">{column_3}</TD>
        </TR>
        </LOOP NAME="table_rows">
</table>
</IF NAME="if_var">

Garbage. Absolute garbage. Honestly, what on earth was I thinking when I wrote that tripe? The idea here is that the tags are parsed by the template engine and an appropriate action taken. So the include tag is replaced by the contents of the file "header.html", and the table is filled with the contents of the "table_rows" variable if the variable "if_var" equates to true.

But whats the point? Check this out:

<?include("header.html")?>

<?if($if_var):?>
<table>
    <?foreach($table_rows as $t):?>
        <tr>
            <td bgcolor="#dddddd"><?=$t['column_1']?></td>
            <td bgcolor="#dddddd"><?=$t['column_2']?></td>
            <td bgcolor="#dddddd"><?=$t['column_3']?></td>
        </tr>
    <?endforeach?>
</table>
<?endif?>

Now how wonderful is that? A true work of art. Could perhaps be even confused with the work of Michaelangelo. Or maybe one of the other turtles. Here we have exactly the same functionality as the previous, at a miniscule of the expense (performance wise), and far, far more extensibility, since all of PHPs galaxial functionality is available. And all you have to do is call include() at the bottom of your script to drag it in. Wonderful.

Now lets dispell a few comments that, doubtless, will be excreted:

  • HTML monkies find PHP too complex.
    Crap. Any HTML monkey that can't handle the above should kill themselves right now, and allow the collective IQ of the world rise a few points.

  • Separation of content from business logic
    Crap. The logic of creating the front end can not be separated, since the front end depends on the logic. If conditions and loops are available in virtually every template engine so this argument is a little moot.

  • Some template engines cache the output, so it improves performance.
    Crap. Don't use a template engine in the first place and you won't have quite such a performance problem. Not only this, but do things the correct way (ie. my way) and your templates will be cached by your php accelerator (you are using an accelerator aren't you?). Bear in mind some accelerators only cache files with a given extension...

So there you go. Don't use template engines, use PHP. Enjoy.

Link to me

If you use any of the code on this site (and if you don't I guess) or it makes your life easier, I'd appreciate a link - http://www.phpguru.org. Thanks.

RSS Feed for Comments

Comments

Author: Richard Heyes
Posted: 30th November 2004 09:00
In that instance I'd probably just use two different templates. Or if the
differences didn't warrant that, some logic in the template.
Quote
Author: Hendy Irawan
Posted: 9th March 2005 13:44
I can understand the reason why so many people hate template engines, as is the guys at Savant. But I'm quite offended the author says it "the correct way".
That implies that everybody else using Smarty, patTemplate, or any other non-pure-PHP template engines are "incorrect"... well at least in your opinion.

While I fully appreciate your honest opinions, I think it's more useful for readers (as you are an authoritative writer) that you do a more objective comparison, giving each one its share of strong and weak points. It's completely acceptable if you bias using pure-PHP templates, but it's not very helpful to just bash other template engine solutions.

And for the last thing, I agree with you that what you've written is "the correct way" to do templating with PHP. But I suggest you to invent a correct way of writing your opinion on your own blog... I love freedom of speech, but I love it more when people make it clear which statements they say are facts and which ones are their own personal opinions.
Quote
Author: Paul M. Jones
Posted: 15th March 2005 13:03
The logic you outline is very similar to the core of Savant. The Savant template system uses PHP for markup, but adds plugins, output filters, multiple search paths, and configurable error objects, all *without* compiling (because the template markup is PHP).

You can read more about Savant here:

http://phpsavant.com/

Thanks for the good articles.
Quote
Author: Peter
Posted: 16th March 2005 04:22
Umm ... so few people in support of template engines. I used HTML::Template and TT2 in Perl where everyone I know, whose code I'd want to work on, uses one or the other or both (you can use both in your app if you want without too much trouble).

I personally find this <?=}<?elsif{<>? just plain dirty. Ugly. Awful. I would believe that using PHP as the template engine will just lead to more of your logic in your presentation.

Writing applications which just work on data structures is a beautiful way to develop. Once you finish with the data model you simpl merge it with the template to return the output. Clean, super easy to debug, super easy to extend.

I have to say that I cannot recall EVER seeing any PHP application which I had any respect for. I avoid 3rd party PHP applications like the plague.

One must wonder why so many langauges support at least ONE templating system .... I've personally never known anyone who wrote CLEAN applications using a template engine to ever go back to a stream of consciousness development method so often found in PHP applications.
Quote
Author: oracle
Posted: 17th March 2005 06:55
Templates are for designers. Designers don't do code. Therefore, templates shouldn't have code whether it be php or a smarty-like mini-language.

I think the best option is to have xml-like declarative tags which are COMPILED into a run-time file with php loops, if/else's, etc.

And no including headers either. That's a job for Dreamweaver libraries. Designers are used to working that way and it's our job to support them.

Designers don't do code.
Quote
Author: Richard Heyes
Posted: 17th March 2005 23:34
oracle:
> Templates are for designers. Designers don't do
> code. Therefore, templates shouldn't have code
> whether it be php or a smarty-like
> mini-language.

I've never worked with a designer who touched HTML. Designers are artists who produced eye candy. HTML Monkies on the other hand, push HTML around, not pixels. If they can't handle the simple syntax illustrated here, then they're not worth their salt.

> I think the best option is to have xml-like
> declarative tags which are COMPILED into a
> run-time file with php loops, if/else's, etc.

I can't see how you'd produce a heavily dynamic site without some sort of logic in the templates.

> And no including headers either. That's a job
> for Dreamweaver libraries. Designers are used
> to working that way and it's our job to support
> them.
>
> Designers don't do code.

Blah.
Quote
Author: Rainer
Posted: 20th March 2005 10:46
Hi Richard,

basically i agree to what you are saying and its exactly what i answered in many boards when someone asks about "template engines".

But... meanwhile i have a problem and dont know how to solve it without a template enginge (different from PHP): i offer some webspace and a forum script for free to "endusers", and the admin of the forum may freely change the templates of the forum layouts.

The problem: i dont know how to avoid that these "admins" do not insert "bad PHP" code in templates (sniffing around, sending tons of emails etc.pp.), as they simply can do EVERYTHING what PHP can do. It would be usefull if there where a possibility to have something like a "restricted include()", what means, that only a very basic subset of PHP commands (echo, for-loop) were "enabled". It dont know how to "restrict" PHP and i dont want to let them insert any (horrible) code - how to overcome that problem?

Regards
Rainer
Quote
Author: maetl
Posted: 21st March 2005 23:58
In many ways, I do agree with these points, and I generally use plain PHP for templates on all dynamic sites that I built

But one of the key aspects of template engines - that I don't think has been mentioned here, is the aspect of code generation or macro functionality which a good template engine has the potential to provide... A good example is the <data:table> tag in WACT, which provides a simple and consistent way to generate HTML table structures simply by mapping to a data source...

Focusing only on control structures and conditionals is a good way to demonstrate that most template engines offer nothing that plain PHP can't do faster and (arguably) cleaner... But there may also be other goals for template engines (laziness perhaps?)
Quote
Author: Richard Heyes
Posted: 22nd March 2005 12:10
maetl:
> But one of the key aspects of template engines
> - that I don't think has been mentioned here,
> is the aspect of code generation or macro
> functionality which a good template engine has
> the potential to provide... A good example is
> the <data:table> tag in WACT, which provides a
> simple and consistent way to generate HTML
> table structures simply by mapping to a data
> source...

Did you forget about functions? :-) Eg. <?=Data_Table($dataSrc)?>

> Focusing only on control structures and
> conditionals is a good way to demonstrate that
> most template engines offer nothing that plain
> PHP can't do faster and (arguably) cleaner...
> But there may also be other goals for template
> engines (laziness perhaps?)

As a programmer I can fully attest to being lazy.
Quote
Author: steve
Posted: 28th April 2005 20:58
i was using smarty but after reading this i don't think there's a need anymore. i was tiring of smarty's "make a new file for a function" plugin system
Quote
Author: PaulG
Posted: 29th April 2005 10:48
Rockon Richard Heyes.

Thanks for putting into words something I could only smell.

Some things you just *know* are wrong instinctively.

OOP, Ajax -- smell sweet to me..

Now lets get to the real stuff, MVC? Can you speak for us all on that?

Keep up the good work and continue the broadcasts from the streets of [where are you in the england then?]
Quote
Author: Thilo Raufeisen
Posted: 30th April 2005 15:52
Templating with PHP is the best way.
Itīs fast and itīs easy. No need to learn a "new language".
But: Seperating the output from the "rest" is still important.
A good Solution is http://www.phpsavant.com
This Templatesystem basically uses outputbuffering in a class. Easy to use and easy to extend.
Quote
Author: Q
Posted: 8th May 2005 22:28
There's still one scenario where a template engine is needed:

if you're developing a LiveJournal/Xanga-esque blog hosting application where 3rd parties will be building templates on your server, you probably want to have an intermediate/interpreted template language as opposed to letting random users execute PHP on your serve 8o
Quote
Author: Jonathan
Posted: 13th May 2005 21:45
The last author has a point about where template langs need to be used.

But you know, I NEVER subscribed to the idea of Smarty, and as a recovering HTML monkey I can't IMAGINE that understanding SMARTY is any easier than understanding basic php data structures like loops.

In fact, I speak from personal experience that it was easier for me to just learn php than it was to pick up the template languages for SMARTY and eZ Publish, and a LOT more fun.

J
Quote
Author: Nolo
Posted: 26th May 2005 16:57
This is something I have wondered about.
Why do you let designers monkey with any of it? Why have your designer actually code the HTML at all? Think about it... Does an interior decorator actually come in and paint the walls? Does an architect pick up a hammer and build the building?

I have always let the designer design the site and then it is my job as the developer to make the page match their mockups in look and feel. This gives us some really fresh page layouts because the designer isn't being limited by what they know about HTML. Sometimes we do have to go back to the designer and work out a comprimise but overall things come out looking like a designer designed it and not like a designer coded it.
Quote
Author: z_malloc
Posted: 31st May 2005 16:15
A couple years back I gave pat template a serious try. After about two weeks, I realized it had essentially created a third task in the project. Worse still, it was a poor syntax implementation to replace good syntax that already existed in PHP. So I shunned templates all together for the next couple years.

Recently, I was coaxed in to trying the PEAR HTML_Template_IT. I have to say I really have enjoyed using it so far. I have worked on large teams developing high concurrency commercial web apps, and when you have HTML developers, and php scripters, it really helps to have code seperation.

Even if your in a small team (ala. yourself), the benifit to a template engine is that your code has zero markup in it. This makes debugging and extending considerably easier on the eyes. Any time you have logic and display in the same view, you create a restriction on modification for both sides. In other words, you'll likely have to modify the logic portion in the event that you need to modify the structural portion of the display. Why fiddle with code that works, even slightly.

After going back and forth and back again in the long debate of templates are good, templates are bad. I can share two points that I think will benefit anybody who bothers to read all this. The first, I pretty much described above.

ABSTRACTION : Even if a little expense is involved. Just like using objects, you'll thank yourself when you revisit or extend it. MVC is the best, but failing that.. fake it as best you can.

SIMPLICITY : This was always a sticking point for me with all the template engines I tried and previewed. Any template engine that performs any tasks beyond simple variable replacement, and structure iteration, has been overbuilt and should be avoided. To phrase it another way, any template engine that creates new syntax is evil. Any template engine that performs logic that is not show or don't show, or evaluates the value of anything defined in the app, is evil.

If you are a sole developer, and you do not use the help of HTML coders, and most importantly, you plan on maintaining everything you write yourself for its lifecycle, by all means, feel free to skip template engines all together. But if you understand the benifits of using objects rather than doing everything procedurally, you'll get a similar warm feeling using the most light weight templating engine you can.

These opinions are my own, your mileage may vary.
Quote
Author: Julian Moors
Posted: 1st June 2005 19:45
Hey Richard!

I actually came to your site to find a way of using a search and replace {tag} function, but found my way onto this page instead. I'm glad I did as this is way better! I'm currently building a commercial application for the first time in PHP and needed a way of maintaining readable code. Also, have you ever thought of making your HTMLTreeMenu JavaScript app in Flash?
Quote
Author: Julian Moors
Posted: 1st June 2005 20:02
Oh and before I forget you've left the end semi-colon in the above code. It should read: <?endif;?>
Quote
Author: Richard Heyes
Posted: 1st June 2005 20:38
Julian Moors:
> Also, have you ever thought of
> making your HTMLTreeMenu JavaScript app in
> Flash?

Are you taking the piss? ;-)

> Oh and before I forget you've left the end
> semi-colon in the above code. It should read:
> <?endif;?>

You don't need the semi-colon. In fact you don't need the semi-colon on the last statement of any block of PHP code when it's followed by the closing "?>".
Quote
Author: Julian Moors
Posted: 1st June 2005 22:46
> Are you taking the piss? ;)

No, actually I'm being serious. Instead of rendering the HTMLTree using JavaScript, why not render out to Flash instead. This may ne a noob thing to say but I'd always thought Flash was used more these days rather than JavaScript solely because people can turn JavaScript off that's all
Quote
Author: Julian Moors
Posted: 1st June 2005 22:54
If you guys are thinking of writing a tinybutstrong replacement/clone then why not use the wysiwyg editor at http://www.fckeditor.net/. Best of all it's free you only have to pay for support.
Quote
Author: Marcus Bointon
Posted: 13th June 2005 14:09
There's one misconception in your article. You say:

"The logic of creating the front end can not be separated, since the front end depends on the logic. If conditions and loops are available in virtually every template engine so this argument is a little mute."

That's a little obtuse on your part. Just because something contains logic doesn't mean it's business logic. There is such a thing as presentation logic - for example I could create a template that displays everything in one big list, and another that paginates it; the only difference between them is presentation logic, and I should not have to even open a business logic file in order to make the change.

Personally I extend the same logic to textual content. My PHP code does not contain any literal text (even error messages) that will ever get to my web pages. Text can only come from two places: from a database dynamically or as static template content. This makes for really easy i18n.

BTW, the word you were looking for is 'moot' not 'mute'.
Quote
Author: Richard Heyes
Posted: 13th June 2005 14:23
Marcus Bointon:
> There's one misconception in your article. You
> say:
>
> "The logic of creating the front end can not be
> separated, since the front end depends on the
> logic. If conditions and loops are available in
> virtually every template engine so this argument
> is a little mute."
>
> That's a little obtuse on your part. Just
> because something contains logic doesn't mean
> it's business logic. There is such a thing as
> presentation logic - for example I could create
> a template that displays everything in one big
> list, and another that paginates it; the only
> difference between them is presentation logic,
> and I should not have to even open a business
> logic file in order to make the change.

And what of the logic that decides which page of your results you're on? Something like the Pager class in PEAR, or similar, has no place in a template and so has to go in your code, which means changing the template (from single list to paged list) will mean changing your "business logic".
Quote
Author: Dave
Posted: 21st June 2005 20:10
Very interesting comments here. Good to see richard standing his ground.
Quote
Author: bsg
Posted: 23rd June 2005 15:36
How expensive is switching from php to html like you're doing there. I know it can't nearly be as expensive as a template system, but I'm curious what kind of performance loss you get.
Quote
Author: Richard Heyes
Posted: 23rd June 2005 15:58
bsg:
> How expensive is switching from php to html like
> you're doing there. I know it can't nearly be
> as expensive as a template system, but I'm
> curious what kind of performance loss you get.

It's not expensive at all. If it was then the traditional idea of PHP (embedded in HTML) would somewhat of a disaster.

IIRC, one of the core developers of PHP mentioned that escaping out of PHP mode and into HTML mode (ie. ?> ... <?php ) produces the same or similar opcodes as a call to "echo".
Quote
Author: bsg
Posted: 2nd August 2005 00:49
Richard Heyes:
> It's not expensive at all. If it was then the
> traditional idea of PHP (embedded in HTML)
> would somewhat of a disaster.
>
> IIRC, one of the core developers of PHP
> mentioned that escaping out of PHP mode and
> into HTML mode (ie. ?> ... <?php ) produces the
> same or similar opcodes as a call to "echo".

But I've read several articles talking about how calling echo numerous times is expensive. Most prefer to concatenate strings to a variable and just echo that variable once. Yes it takes more memory, but isn't it worth it if it finishes 25%-50% faster.

here is one old article that mentions it, i remember reading a few others but I lost them :(
http://www.phplens.com/lens/php-book/optimizing-debugging-php.php
Quote
Author: 45
Posted: 5th August 2005 17:47
Mark:
> I agree with the first poster... the way I use
> your old template engine is
> to initialize a bunch of vars, then call a page
> to parse them.
>
> Sometimes, I use up to 4-5 different look and
> feels with the same content,
> displayed differently, but passed from those
> very same vars.
>
> It's easy to just parse the template and =
> whatever i want and return the
> content to the page.
>
> Really, if I wasn't lazy, I could just build
> something myself to accomplish
> this... but then again, it's already done in
> your first template engine
> isn't it? ;)
Quote
Author: Pablo
Posted: 6th September 2005 16:43
I tend to agree with you, Hayes, but only when it comes to sites and simple web-based applications.

Complex portals, CMS extensions/skins, Workflow Systems/Engines (Galaxia for example), really need a templating system for the sake of
mantainance.

The assumption that there IS only one and right way of solving problems is a bit dangerous when we are talking about computer programming.

Cheers,
Pablo
Quote
Author: Brad
Posted: 7th September 2005 00:13
Smarty!! Template engines make things 100% easy, faster, cleaner code!! Include files are great for includes, not to build a web site, maybe in 1990 this was a good ideal...not anymore folks.
Quote
Author: Richard Heyes
Posted: 7th September 2005 20:44
Brad:
> Smarty!! Template engines make things
> 100% easy,

Wrong.

> faster,

Oh so wrong.

> cleaner code!!

And wrong.

> Include files are great
> for includes, not to build a web site, maybe
> in 1990 this was a good ideal...not anymore
> folks.

Stop reading phpbuilder.com.
Quote
Author: Nash
Posted: 20th October 2005 21:51
Hi Richard et al,

Interesting thread going on here.
I was looking for the mail script you had for download here and stumbled upon this article.

For most comments here there's something to say.
I have written my own template engine and language (I love reinventing the wheel in different colors and shapes) some time ago. It works pretty well but cost quite a lot of time and effort to make it nice.
If I have to make a site all on my own (someone passes me the HTML and I make it all dynamic) then I would choose Richards way of doing. Include (or require) a file containing HTML and PHP code and use the PHP code to fix everything up. Works perfectly fine and probably saves processor time.. in any case, it'll allow you do to anything you please. From clean code to ugly hacks.

If I have to work with an HTML monkey or a designer, I prefer to work with the templates. Mainly because most people are afraid of programming language statements and because I don't want their syntax statements to ruin my code!

So, for coders and for well educated HTML monkeys I would recommend the above.
Quote
Author: James
Posted: 31st October 2005 17:44
casey:
> I agree on the use of php in your html, but what
> if you want to use several
> layouts or interfaces for the same page?

My custom framework does it like this:

To use the default template:

$Application->Response->Render();

To use a custom template:

$Application->Response->Render('/path/to/custom/template.php');

Richard is spot on about using PHP alternate syntax in templates. Why go to the additional overhead of parsing a proprietary markup language when the PHP syntax is just as easy to learn?
Quote
Author: IceTheNet
Posted: 15th November 2005 04:59
well I am building a user editable template and though of using php but then if I let users a php template they could and mostlikly would inject bad code and possibly destroy my server. That is a good use for a template. then users can edit and you don't get hacked unless you get the dreaded html exploit.
Quote
Author: Henri
Posted: 20th November 2005 02:19
The problem is that if you make your template "open" to anyone... then it is a simple matter for them to "see" any variables or values that you might want to keep hidden.

For example, let's say you have a $_SESSION['username'] value set. Now it is possible for the person to edit the include php file and do this:

echo print_r($_SESSION);

Thus, they can see how you're setting the username for the program...

.. and then they can override it easily to become a different user.

Just an example.. but what if you had "features" of your program defined by using the session variable, or whatever.

The ability to use template abstraction is good only because it thus does not allow anyone to modify your include "template" file and execute arbitrary code.

Quote
Author: Petar Mari&#263;
Posted: 27th November 2005 11:01
Honestly, I don't quite get your "arguments". Sure there are times you should or shouldn't use templates - but you musn't generalize things, and above all make your main arguments be emotions and/or insults.

I would advise you to take a look at django http://www.djangoproject.com/, that is if you can handle the thought of it using and been made with Python. They made some pretty cool stuff, especially with the bundled template engine - I've never seen something as simple functional and simple to use as it. And trust me, I've seen a lot of them.
Think RAD is just a buzzword? Not any more it isn't - it's a reality ;)

Just my 2e-2 euros.
Quote
Author: Bastian Frank
Posted: 14th March 2006 08:08

Yes! A very good article! I am never tired of telling everyone that PHP IS ITSELF a template scripting language and every artificial templating system is unnecessary.


The splitting of Logic and Presentation, or the good old MVC pattern, is a question of concept and logic in mind, and it is NEVER bound to a specific technology like templates.


It is worth to think about the technology (pure PHP, XML, "Templates", JSP?) in every new project.

Quote
Author: z_malloc
Posted: 14th March 2006 17:26
I've used this approach recently with a group of developers on a large scale project. There is one fairly large shortcoming with this approach. Namespace collision becomes very real when your project is of any scale, and you have many developers working in independantly. The solution we went to was to isolate variable scope through controllers. The end result is that each template (markup fragment) has its own scope. It still maintains two very important fundamentals. No keyword/variable replacement logic, and no introduction of a lightweight templating "language". End result...

Pure PHP, simple variable output handling, scope and namespace isolation.
Quote
Author: brad
Posted: 9th October 2007 22:08
i also hate smarty or any other temp engine that is not standard EXCEPT the holy XML-XSL VIVA XML
Quote
Author: gble
Posted: 10th October 2007 13:22
I quite disagree with this article:
depending with what you want to do and who will have to do it:
if you are doing the project by yourself or with one or 2 developper friends, then that's certainly the easiest/quickest and cleanest way.

security wise:

template language are more secure:
unless you do everything yourself, people have responsability. The lead developper of a core application is directly responsible of his code and you don't want to dissolve the risk by enabling any designer / html integrator to put bugs, holes or any php / sql language directly in it.

templating system, like smarty are very useful for big projects when each one is responsible of one field of work.

Then template can be your own templating system made with php, can be smarty or can be xml/xslt it doesn't change anything, and in terms of performance, this is really not a problem.

(I heard facebook is using smarty, and I guess it's a quite good idea as their system is quite complex and evolutive)
Quote

Post Comment

Your name:
Your email:
(Don't worry, I won't spam you. Also, if you do put your email address in here, you'll get notified of new comments. If you don't, you won't.)
Comments:
  Do not post support type questions please

 
CAPTCHA image If you can't read the CAPTCHA then press the submit button to get another. Your comment will re-appear (as if by magic...).
Captcha image
Last modified: 17:01 29th December 2006