Thursday, February 7th, 2008

Django Template Language in JavaScript

Category: Dojo, Examples, JavaScript

I am learning at lot at the Dojo Developers Day one. Whenever I met Dojo folks I get the impression that there are 55 gems in the library that I have no idea about!

One of them is Neil Roberts implementation of the Django template language in JavaScript.

His work lives in dojox.dtl and you can check out a simple demo that renders, and rerenders a page with new content as you add it:

  1. <html>
  2. <head>
  3.     <title>Demo using dojox.dtl._Templated</title>
  4.   <script type="text/javascript" src="../../../dojo/dojo.js"
  5.         djConfig="isDebug: true, parseOnLoad: true"></script>
  6.   <script type="text/javascript" src="../../../dijit/dijit.js"></script>
  7.   <script type="text/javascript">
  8.     dojo.require("dojox.dtl._Templated");
  9.  
  10.     dojo.declare("Fruit", [dijit._Widget, dojox.dtl._Templated], {
  11.         oldRepl: "some value for testing the old style template substitution",
  12.         _dijitTemplateCompat: true,
  13.         items: ["apple", "banana", "orange"],
  14.         keyUp: function(e){
  15.             if (e.keyCode == dojo.keys.ENTER) {
  16.                 var i = dojo.indexOf(this.items, e.target.value);
  17.                 if (i != -1){
  18.                     this.items.splice(i, 1);
  19.                 } else {
  20.                     this.items.push(e.target.value);
  21.                 }
  22.                 e.target.value = "";
  23.                 this.render();
  24.                 dojo.query("input", this.domNode).forEach("item.focus();");
  25.             }
  26.         },
  27.         templateString: '<div><input dojoAttachEvent="onkeyup: keyUp"/><ul>{% for item in items %}<li>{{ item }} ${oldRepl}</li>{% endfor %}</ul></div>'
  28.     });
  29.  
  30.   dojo.require("dojo.parser");
  31.   </script>
  32.  
  33.     <body>
  34.         <div dojoType="Fruit"></div>.
  35.     </body>
  36.  
  37. </head>
  38. </html>

You can also see another interesting example which is a blog view. Take a view source on that puppy.

Posted by Dion Almaer at 2:47 pm
10 Comments

++++-
4 rating from 33 votes

10 Comments »

Comments feed TrackBack URI

It is why understanding the gap between professional tools (YUI/Dojo) and hobbyist tools (Prototype/jQuery) is so hard for people on either side of the equation.

Prototype / jQuery hobbyist tools? hahahaha.
Again people are mixing up the difference between a library and a toolkit. I must be pretty unprofessional to not want to weigh down my apps with YUI’s or Dojo’s bloat.

Comment by naterkane — February 7, 2008

“Dojo’s bloat”?

dojo.js is 23K. The new template system is 6K (gzipped), and both dojo.js and the dtl system are optimized to the hilt. Not only is Dojo not bloated, it’s downright tiny for the amazing features you get…and we give you serious optimization tools to keep your app light and fast.

Regards

Comment by slightlyoff — February 7, 2008

i was put off my that comment too. as a “professional” web developer, i’ve used dojo and jquery on client projects. (not at the same time of course). i found jQuery to be easy to learn and well documented. i could not say the same for dojo. maybe things would have been more pleasant if dojo’s documentation was more “professional”.

Comment by mundizzle — February 7, 2008

You’re missing the point: the point is an implementation of Django Template Language in JS, regardless of what the opinions that the author of that script has in the context of a blog post.

Comment by Tom Trenka — February 7, 2008

There’s a lightweight templating library that is in my very biased opinion, easier to use: Embedded JavaScript

Comment by JustinMeyer — February 7, 2008

@mundizzle. Have you looked at the online Dojo book the last year? It’s chock-full of goodies right now, and getting bigger every month. Try the chapter on Layout, for instance;

http://dojotoolkit.org/book/dojo-book-0-9/part-2-dijit/layout

Cheers,
PS (Biased fanboy, but what the hey :)

Comment by peter svensson — February 8, 2008

Justin:

This templating language only needs you to dojo.require(“dojox.dtl”), at which point you can use it irrespective of the Dojo Widget System (aka: Dijit). Since (like all things in Dojo), it’s a layered design, you can use this templating anywhere, including in dojo.query() results. Check it out:

dojo.require(“dojox.dtl.ext-dojo.NodeList”);
dojo.query(“div > span.thinger > ul”).dtl(
“{{ objectvalue }}”,
{ objectvalue: ‘anything you want’ }
);

Comment by slightlyoff — February 8, 2008

Slightlyoff,
I’m slightly confused by your example. I think it puts “anything you want” in a ul object. Is this correct?

In the spirit of cooperation, I’ll cautiously list a few nice things about EJS. I’m not trying to be competitive. I hope that dojo can include a few of these (if it doesn’t already) in its toolkit.

EJS gives you a few options on where the template comes from:

Text: new EJS({text: ”})
Element: new EJS({element: document.getElementById(‘template’)})
File: new EJS({url: ‘/template.ejs’})

EJS templates can use 2 different magic tags or ${}.
EJS caches templates.
EJS can use JSLint for Debugging.
EJS has rails-like view helpers.

EJS also has many options for rendering:

Render and get back text: txt = new EJS({text: ”}).render({objectvalue: ‘anything you want’})

Update an element (I’m using prototype selector):
new EJS({text: ”}).update($$(‘div span.thinger ul’),{objectvalue: ‘anything you want’})

Update an element with the results from a JSON ajax request:
new EJS({url:’/todo.ejs’}).update(‘todo’,’/todo.json’)

I find debugging and loading from a file to be the most helpful features of EJS.

There’s also jMVC (http://blog.codeville.net/category/jmvc/) which is syntactically like EJS, but w/ less functionality. BUT, it allows continuations. If you have any other thoughts: j u s t i n at j u p i t e r dot c o m.

Comment by JustinMeyer — February 9, 2008

hey Justin,

So Dojo’s DTL implementation has a lot of the features you mention, but there is at least one large philosophical difference, namely that Django’s templating language keeps code out of templates, and so Dojo’s implementation follows suit. As with Dojo’s existing templating system, the goal is to allow developers and designers to iterate on templates independent of each other and given how successful folks have been with the existing system, this seems to have been a good choice although I totally get that reasonable people can disagree on this one. Templating is hard, and hard to satisfy everyone with.

As for the features you list, I think all of them are available in Dojo in some way, although the syntax may not be as terse for some, and because the design of Dojo is layered, not everything comes through a single object. I’ll send you mail.

Regards

Comment by slightlyoff — February 11, 2008

This is very similar to what the Yz javascript django template compiler is trying to do: http://github.com/comolongo/Yz-Javascript-Django-Template-Compiler. (Disclaimer: I am the main contributer to this project) Except instead of parsing the template on the clientside on each pageload, the yz javascript template compiler just compiles the template on the serverside once during the build process into an optimized javascript function. With all of the heavy lifting done, the compiled function just does basic concatenation of the template strings and variables so it has much better performance and responsiveness . Another benefit is that the compiled functions are in pure javascript so there are no external dependencies; people who use jQuery, YUI, mootools, etc. could all use this solution without any problem. This JS perfs test shows that it is around 10x faster than several other templating solutions, including John Resig’s simple templates: http://jsperf.com/javascript-templating/2.

The yz javascript django compiler is still in heavy development, currently it has support for only basic tags and filters, e.g. if tag, for loop tag, default filter, add filter, etc.
Here is a simple demo of some of its features: http://yz-demos.appspot.com/yz_djs_demo/

Comment by weissinicht — September 15, 2010

Leave a comment

You must be logged in to post a comment.