Skip to content


Ajax; Templating; and the Separation of Layout and Logic

The Background

I have often mentioned my process of expanding my proficiency of Ajax. Through my journey I have made a number of wrong turns and hit my share of stumbling blocks. All of that has been a learning experience and I'm learning still. I began fiddling with XMLHttpRequest as many do - blissfully ignorant of the many frameworks that exist to make Ajax super easy. My code was bloated with some neat...'features' (pronounced: bugs).

Then I discovered the Simple Ajax Toolkit (SAJAX), which was simpler than doing raw XMLHttpRequest but really not all that simple. My latest step into the world of Ajax, and the toolkit that holds my love (currently) is Prototype...and I like my Prototype served with a side of Script.aculo.us. *drool* UPDATE: I now use jQuery for all my Ajax and DOM manipulation goodness.

While Ajax is the cause for the article, the heavy focus is on templating. For the past few years I have been using XTemplate as my templating library (I'm a PHP buff) and have been happily separating my logic from my layout...unitl I ran smack dab into the power of Javascript. My PHP still kept its separation from HTML as is the purpose of XTemplate, but it was my HTML that became littered with little nuggets of Javascript all over the place. No matter the method to my Ajax madness, this was my problem.

What Exactly Is Templating And Why Do It?

Templating is definately not new and its use has been debated back and forth for quite some time. But like I stated above, the goal of templating is to keep logic separate from layout which is a good thing for a couple of reasons:

  1. Less clutter. Face it, HTML and whatever server-side scripting language you choose to use are two different beasts. Mixing them together is visually unappealing making code hard to read...and hard to read code is hard to debug.
  2. Coders can develop code. Designers can develop layout. With templating, you are able to achieve this separation and avoid the need for a developer to butcher a designer's layout to make it function with an application. Each can design/code on their own then combine their efforts with ease.
  3. With separation such as this, applications are more easily skinned and/or receptive to complete UI overhauls.
  4. Did I mention less clutter?

Let me give you an example of what I mean with a simple Goodbye Cruel World application:

Here's the PHP script: goodbye.php

PHP:
  1. <?php
  2. include('xtemplates.php');
  3.  
  4. $tpl=new XTemplate('goodbye.tpl');
  5. $tpl->assign('CHEEZEWHIZ','Bork, bork, bork!');
  6.  
  7. $tpl->parse('main');
  8. $tpl->out('main');
  9. ?>

Here's the Template: goodbye.tpl

HTML:
  1. <!-- BEGIN: main -->
  2.   <div style="font-size:18px;font-weight:bold;">Goodbye Cruel World! {CHEEZEWHIZ}</div>
  3. <!-- END: main -->

Here's the output:

Goodbye Cruel World! Bork, bork, bork!

Obviously that is an extremely simplistic example. With XTemplates I can get pretty complex and include files, loop over and parse out some complex block structures, assign arrays into template variables, etc. If you want to see a more complex example of a template, check it out here.

Templating Seems Sexy, How Does It Work In An Ajax-ified Environment?

I thought you'd never ask. For this, I have created a diagram to detail how I combine Ajax, PHP, and Templating all in one.


ajax_with_templating.gif

It all works like this:

  1. A User makes a request to view a page
  2. The server-side script calls a series of application functions that generate blocks of templates
    1. Each section that can be updated/rendered by Ajax calls are separated into their own templates, which enables them to be called on initial page load and separate Ajax-triggered calls from the client.
  3. The complete template blocks are sent to the user as a rendered page.
  4. As the user interacts with the interface, two specific things can occur:
    1. An Ajax.Updater (see Script.aculo.us) is triggered, which makes an Ajax callout. The callout is sent to the Ajax Handler (which is a PHP script) which handles the call and invokes the appropriate application functions. Those functions initialize template blocks and output HTML. The HTML output by the server is received by the client and inserted into the User Interface.
    2. An Ajax.Request (see Script.aculo.us) is triggered, which makes an Ajax callout. The callout is sent to the Ajax Handler (which is a PHP script) which handles the call and invokes the appropriate application functions. No templates are initialized or output to the client...instead, the client manipulates the DOM on its own to give proper feedback to the user.
  5. Rinse and repeat as needed.

If we keep all HTML within templates and use modularized functions to initialize and render those templates, we achieve extreme layout/code reuse.

Sounds Cool...So What's The Problem?

Well, a server-side scripting language coupled with a templating engine is all well and good. But if as we throw Ajax into the mix, suddenly we are working with a lot of Javascript in addition to the a server-side language and HTML. Through my journey in Ajax development my templates - which were havens away from code - were overrun with Javascript code! Eegad.

Now, don't worry. I place my Javascript in separate Javascript files and include them where appropriate with ye olde <script> tag, which I have done from the beginning. No, the issue has been handling user events; onClick, onMouseOver, onMouseOut, etc. Ajax functions primarily based on user interaction, so onClicks and whatnot are core. My templates soon began to look like this:

HTML:
  1. <!-- BEGIN: stuff -->
  2.   <div>[<a href="javascript:void(0);" onClick="Element.show('add_item');">Add</a>]</div>
  3.   <div id="add_item" style="display:none;">
  4.     <form id="add_item_form" onSubmit="Ajax.Request('ajax.php?'+Form.serialize('add_item_form'),{method: 'post'});return false;">
  5.       Name: <input type="text" name="name"/> <input type="submit" value="save"/> <input type="reset" value="cancel" onClick="Element.hide('add_item');"/>
  6.     </form>
  7.   </div>
  8. </div>
  9. <!-- END: stuff -->

As you can see, the once separate layout was laden with code.

The Solution

In a fully layout separate from logic in an Ajax environment, you need to make use of Javascript event handlers. My personal choice is Behaviour which my friend, Zach, posted about yesterday.

Behaviour (coupled with Prototype) gives you easy-to-follow separation of javascript and HTML. Hugely cool. Hugely useful. Here's an example:

The HTML:

HTML:
  1. <ul id="example">
  2.   <li>
  3.     <a href="/someurl">Click me to delete me</a>
  4.   </li>
  5. </ul>

The Javascript:

JavaScript:
  1. var myrules = {
  2.   '#example li' : function(el){
  3.     el.onclick = function(){
  4.       Element.removeChild(this);
  5.     }
  6.   }
  7. };
  8.  
  9. Behaviour.register(myrules);

That example creates a bulleted list (as is readily obvious in the HTML code). What nifty is the Behaviour Javascript logic. myrules says that any <li> tag with a parent id of #example will have an onclick that causes the li tag to be removed.

And of course, besides Behaviour there is a slew of other solutions that when combined together make for a sweet, modularized, separated solution. Here's what I use for my PHP/Ajax applications:

Here are some standards I stick to:

  • Keep CSS (.css) styles separate from the Template files
  • Keep JavaScript (.js) files separate from Template files
  • Keep HTML in the Template, don't spatter it around the PHP scripts
  • Modularize as much as possible
  • Heavy Code reuse

The Drawbacks

Obviously in a Templated/Event Handled environment there are some drawbacks and I'd be stupid not to mention them. Here goes:

  • There is some overhead when using a templating engine. With XTemplate, the layout engine is a PHP class that loads the template and parses through it as dictated by the application functions
  • True separation - separating out your Javascript into .js files, your CSS into .css files, your server-side scripts into various files (the initial script, a functions script, and your ajax handler(s)), and your layout into template files - generates a lot of files to deal with. The larger your application, the more you will need to micro-manage the organization of these files, which in and of itself can be a daunting task.
  • Ummm...I can't think of any more just yet. I'm sure more will come when I've lived in this environment a lot longer.

Summary

Layout and Logic separation is a beautiful thing; keeping one language from another has some true value in readability. To do it half-way gains you nothing. True separation has been a blessing in my development and debugging. If you haven't at least tried it, check it out, it may be what you were looking for (even if you didn't know it).

Oh and a definate Kudos to Zach Tirrell for starting me down the road of templating and Gmail/Google Maps/Casey Bisson for driving me to check out Ajax.

Posted in Blog, Technology.

Tagged with , , , , , , , , , , , , , , , , , .


240 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. betsson says

    nice post. thanks a lot.

  2. gay sohbet says

    thanks you admın

  3. direkizle says

    I totlaty agre with following sentence:

    “We all know there are a lot of really great engineers and people at Microsoft working for Open Standards, but Open Standards like so much of what the company has produced over the years? ActiveX, DotNet, JScript, VBScript, C# (The “Open Standard” Java Crusher), this is good idea”

    Great Job!

  4. sinema izle says

    ı have followed your writing for a long time.really you have given very successful information.
    In spite of my english trouale,I am trying to read and understand your writing.
    And ı am following frequently.I hope that you will be with us together with much more scharings.
    I hope that your success will go on.

  5. security says

    very thanks men

  6. klip izle says

    Thanks for this post and other posts Really usefull..

  7. domuz gribi says

    Development. XHTML, CSS, Javascript, PHP and MySQL…I do it all, however, I did not learn them all at once…but over a series of years. I think the key concept is to really try and keep your logic from your design – keep the MySQL/PHP side of things separate from the XHTML/CSS side

  8. muri says

    thank you very much men. great info you provide us.

  9. 招商加盟 says

    At Plymouth State we work in a multi-server environment and often wish to display dynamic content from one server in an Ajax-like fashion on another server’s website. My co-worker, Zach Tirrell, and I have drummed up a solution that works to keep our layout and logic separate, while still serving our end users in a smooth, seamless, non-iFramed

  10. muzik dinle says

    thanks so much. greetingz from Turkey

  11. Berik says

    using XTemplates, PHP and Ajax after the request is returned in full the entire template (duplicated), instead of the desired element, help please why this is happening and how to avoid it.

    Sorry for my English from Google Translate)

  12. dillon says

    awesome article, seriously i have to start structuring my code like this

  13. 外汇 says

    fx serves

  14. muzik dinle says

    thanks so much. greetingz

  15. oyun turnuvasi says

    do u know ajax tabs meaning? If yes can you say to me it how is it working :(

  16. firma rehberi says

    firma rehberi dir

  17. halıyıkama says

    halıyıkama da üstün firma

  18. davetiye says

    davetiye de tek firma

  19. hurda says

    her türlü hurda ihtiyaçlarınızda http://www.yilmasinlarmetal.com hizmetinizde

  20. hurdaci says

    hurdacı arıyorsanız http://www.hurdaci.biz hizmetinizde

  21. ferforje says

    ferforje de çözüm noktası http://www.yalkinferforje.com hizmetinizde

  22. izle says

    While Ajax is the cause for the article, the heavy focus is on templating. For the past few years I have been using XTemplate as my templating library (I’m a PHP buff) and have been happily separating my logic from my layout…unitl I ran smack dab in…
    thanks admin nice shahring

1 ... 3 4 5

Continuing the Discussion

  1. Ajaxian » Ajax Templating - Seperation of Layout and Logic linked to this post on March 14, 2006

    [...] In this informative blog entry, BorkWeb.com shares a method for creating a templating system generated wholely with Ajax and PHP. While Ajax is the cause for the article, the heavy focus is on templating. For the past few years I have been using XTemplate as my templating library (I’m a PHP buff) and have been happily separating my logic from my layout…unitl I ran smack dab into the power of Javascript. My PHP still kept its separation from HTML as is the purpose of XTemplate, but it was my HTML that became littered with little nuggets of Javascript all over the place. No matter the method to my Ajax madness, this was my problem. [...]

  2. Sam’s random musings » Ajax Templating - Separation of Layout and Logic linked to this post on March 14, 2006

    [...] rel=”lightbox”> In this informative blog entry, BorkWeb.com shares a method for creating a templating system generated wholely with Ajax and PHP. [...]

  3. Neil Mix » linked to this post on March 18, 2006

    [...] Interesting while not too surprising: behaviors are a great way of separating logic and content. I guess those wacky Microsoft people might have had a clue after all. And they even used CSS selectors to manage the application of behavior to elements. I’ve always marveled at the design of I.E. DHTML behaviors. WAY ahead of its time. [...]

  4. warpedvisions.org » Blog Archive » Ajax and templating linked to this post on March 18, 2006

    [...] March 18th, 2006 in Links An article on Ajax; Templating; and the Separation of Layout and Logic. [...]

  5. aNieto2K | De todo un poco » Lo último de lo último en Ajax linked to this post on March 19, 2006

    [...] El ajax en Templates Pretenden separar el layout de la lógica … demasiado complejo [...]

  6. Wordpress » Blog Archive » Ajax Templating - Separation of Layout and Logic linked to this post on March 19, 2006

    [...] In this informative blog entry, BorkWeb.com shares a method for creating a templating system generated wholely with Ajax and PHP. While Ajax is the cause for the article, the heavy focus is on templating. For the past few years I have been using XTemplate as my templating library (I’m a PHP buff) and have been happily separating my logic from my layout…unitl I ran smack dab into the power of Javascript. My PHP still kept its separation from HTML as is the purpose of XTemplate, but it was my HTML that became littered with little nuggets of Javascript all over the place. No matter the method to my Ajax madness, this was my problem. [...]

  7. BorkWeb » Oooo event:Selectors for Prototype linked to this post on March 21, 2006

    [...] My article on the Separation of Layout and Logic touched on a key point of heavy Javascript use in an Ajax rich environment…the need for separation of Javascript code – namely events – from the HTML. Behaviour was my suggested CSS/Javascript event selector framework. [...]

  8. BorkWeb » A Simple Server-Side Ajax Handler linked to this post on March 22, 2006

    [...] In my recent post on ‘Ajax; Templating; and the Separation of Layout and Logic,’ I refer to an Ajax Handler that sits server side to handle Ajax calls. Some elaboration is in order. [...]

  9. Ajaxian » Writing Your Server-Side Ajax Handler linked to this post on March 23, 2006

    [...] Following up on his previous article on Ajax templating, Matthew Batchelder has posted the other half of the equation – the PHP script that responds to the Ajax requests. In my recent post on ‘Ajax; Templating; and the Separation of Layout and Logic,’ I refer to an Ajax Handler that sits server side to handle Ajax calls. Some elaboration is in order. [...]

  10. BorkWeb » Practicing What I Preach linked to this post on March 24, 2006

    [...] MasterWish was built using SAJAX as the tool of choice for Ajax communication but as I’ve mentioned in the past, I am a Prototype convert. My knowledge of Ajax, JSON, and general application structure has been morphing so much in recent weeks that I have held off in completely revamping the wish list site. [...]

  11. WiredPress » Archive du blog » 웹서비스 플랫폼 linked to this post on March 24, 2006

    [...] BorkWeb.com에서 웹2.0의 주요 구현 기술 플랫폼을 나타내는 한장의 그림을 보았다. 클라이언트-서버기반 기술은 여전하지만 아래의 그림을 보면 Ajax 플랫폼이 특징이라고 할 수 있다. 조만간 Ajax 플랫폼들이 나올 것이라고 한다. 그러나 무엇보다도 중요한 것은 고객의 경험이 우선이라는 것이다. 경험을 극대화할 수 있는 서비스와 플랫폼이 사랑(?)받을 것으로 본다. 그것이 유선 서비스이든 무선 서비스이든… [...]

  12. Anonymous linked to this post on March 26, 2006

    BorkWeb Ajax; Templating; and the Separation of Layout and Logic…

    While Ajax is the cause for the article, the heavy focus is on templating. For the past few years I have been using XTemplate as my templating library (I’m a PHP buff) and have been happily separating my logic from my layout…unitl I ran smack dab in…

  13. One Measly Dollar » Blog Archive » links for 2006-03-25 linked to this post on March 27, 2006

    [...] Ajax; Templating; and the Separation of Layout and Logic Responding to Ajax calls with a PHP script. (tags: ajax php howto) [...]

  14. dhruba.net :: Binary Thoughts » Client side templating and its implications on Web application development linked to this post on May 1, 2006

    [...] “What on earth is that” was my first reaction when I read about it. In fact what I am talking about here is the complete separation between JS and HTML. Your initial reaction might be, as mine was, to ask why? Surely, client-side code doesn’t need to be separated from client-side code? Does it? Surely it becomes even less compelling when you’ve got the same developer working on both which is normally the case? Is this separation even possible given that JS must latch onto event declarations in HTML in order to act upon them? [...]

  15. Schone HTML met Javascript | Scriptorama linked to this post on July 7, 2006

    [...] Deze ‘rules’ gelden voor id “list” en bijbehorende list items (<li>). Bij een onclick event wordt de functie click() aangeroepen. Dankzij Behaviour worden er bij kliks op de links functie click() aangeroepen en dit allemaal zonder enig Javascript code in de HTML. Let wel op dat je de bestanden op de juiste volgorde binnenhaalt! Je kunt natuurlijk meerdere rules aanmaken en ook andere events gebruiken. Zie de Behaviour documentatie voor meer informatie. Naast de eerder genoemde voordelen, heb je in feite ook je Javascript logica gescheiden van je HTML presentatie. Met andere woorden, een simpele template engine. Op Borkweb vind je een uitgebreide AJAX template engine, zeer net! Natuurlijk met Behaviour en iedereens favoriete Javascript library Prototype. [...]

  16. BorkWeb » Learning What I Know linked to this post on August 15, 2006

    [...] Development. XHTML, CSS, Javascript, PHP and MySQL…I do it all, however, I did not learn them all at once…but over a series of years. I think the key concept is to really try and keep your logic from your design – keep the MySQL/PHP side of things separate from the XHTML/CSS side of things ( e.g. Ajax, Templating, and the Separation of Layout and Logic). Javascript is a bit of a wildcard and bridges between both the presentation and logic. [...]

  17. BorkWeb » Remote JavaScripting Example - Part I linked to this post on September 22, 2006

    [...] At Plymouth State we work in a multi-server environment and often wish to display dynamic content from one server in an Ajax-like fashion on another server’s website. My co-worker, Zach Tirrell, and I have drummed up a solution that works to keep our layout and logic separate, while still serving our end users in a smooth, seamless, non-iFramed manner. [...]

  18. BorkWeb » The Ajax Experience linked to this post on October 10, 2006

    [...] MasterWish – a one and a half year old brainchild of a couple of other developers and myself – has been my playground after work hours. I began my experimentation with Ajax using that site, as PSU tended to slap my hand when looking into Ajax at work. Through that experimentation, I began to understand the workings of Ajax and how it would work into the PHP/Templating environment I was so comfortable with. Once I had dug down, I promptly posted my “Ajax; Templating; and the Separation of Layout and Logic” article that Ajaxian blogged about, along with the follow-up article. [...]



Some HTML is OK

or, reply to this post via trackback.