Search code examples
javascriptbrowserdust.js

Browser side Dust.js


I've been trying to put together a really simple example using Dust.js in the Browser. Although the docs are very good there doesn't seem to be much information on getting things configured in the for browser.

So based on the following JSON data taken from the Linked-In Dust tutorial:

https://github.com/linkedin/dustjs/wiki/Dust-Tutorial#wiki-Show_me_some_Dust

{
   "title": "Famous People", 
   "names" : [{ "name": "Larry" },{ "name": "Curly" },{ "name": "Moe" }]
}

And this template:

 {title}
 <ul>
 {#names}
 <li>{name}</li>{~n}
 {/names}
  </ul>

How can this be sent up for rendering client side in the browser?


Solution

  • A little bit down on the page you will find a basic example how to compile a template:
    Compiling a Dust Template

    Basically you just have to call the compile function to register the template.

    var compiled = dust.compile("Hello {name}!", "intro");
    

    To use it immediately, execute loadSource to write the compiled template into dust's template library:

    dust.loadSource(compiled);
    

    Then you're able to render the template with your JSON-data:

    dust.render("intro", {name: "Fred"}, function(err, out) {
        console.log(out);
    
        // or maybe with jquery:
        $('#container').html(out);
    });