node.jsdust.jsclient-side-templating

how to use dustjs-linkedin as client side templating?


I get the idea of server and client side templating, but dust.js confuses me a little bit.

In order to use dust.js for client side templating, you need three steps:

  1. complie the template
  2. load the template
  3. render the template

Right?

But where do the templates come from? I saw two different methods:

 1. <script> template <script>
 2. <div> template </div>

... Both of them are in the DOM. Which is correct?

I also notice that you can load the template via ajax, so the template won't be seen in the DOM, but I don't know how to do that.

Also, I'm currently using jade as express view engine. Is it necessary to switch to dust.js? What is the advantage?


Solution

  • This is LinkedIn Dust JS wiki page that can answer your questions and has very good examples: http://linkedin.github.com/dustjs/

    But to answer your questions here:

    Yes you need to compile your dust template which becomes a JavaScript file that you can add to your page by <script> tag and then call dust.render method to render your template. Here is an example:

    1. write following code in a template file and save it as sample.tl

      <p>Hi {firstName} {lastName}</p>
      
    2. compile sample.tl to sample.js by dustc sample.tl in command line or use dust.compile("your_template_code", "template_name") to compile the template and save the output in a JavaScript file (sample.js) or you use duster.js to watch and compile templates by nodejs: https://github.com/dmix/dusterjs

    3. add sample.js in your html:

      <script type="text/javascript" src="sample.js"></script>
      

      this will also register your template to dust.cache.

    4. in your JavaScript:

      var your_json = {firstName:'James', lastName:'Smith'};
      
      dust.render('sample', your_json, function(err, out){
      
          your_dom_element.innerHTML = out;
      
      });
      

      The result of above dust.render method will be <p>Hi James Smith</p>

      So you need to pass 3 arguments to dust.render: dust.render(template_name, json, callback)