1
votes

All the template engines I know use a <script> tag to include custom templates in the page. For example, JsRender:

<script id="theTmpl" type="text/x-jsrender">

    <div>
       <em>Name:</em> {{:name}}
       {{if showNickname && nickname}}
          (Goes by <em>{{:nickname}}</em>)
       {{/if}}
    </div>

</script>

Then I can dynamically use this template to refresh elements of a page:

var template = $.templates("#theTmpl");
var htmlOutput = template.render(data);
$("#result").html(htmlOutput);

However, I don't understand how client Dust.js works. How to have custom Dust.js templates on my page? How to dynamically render a content into them and put the result on the page?

1

1 Answers

3
votes

Dust templates can be included in script tags on the page, and that works well for experimentation and testing. The template would look something like:

<script id="theTmpl" type="text/x-dust">

    <div>
       <em>Name:</em> {name}
       {?showNickname}
          {?nickname}
            (Goes by <em>{nickname}</em>)
         {/nickname}
      {/showNickname}
    </div>

</script>

And the JavaScript would look something like this:

// Get the template content
var template = $('#theTmpl').html();
// Compile the template into JavaScript string
var compiledTemplate = dust.compile(template, 'nicknameTemplate');
// Execute the JavaScript string and register the template within Dust
dust.loadSource(compiledTemplate);

var data = {
  name: 'Green',
  nickname: 'Dust guy',
  showNickname: true
};

// Render the template with template name, data, and a callback function
// (because Dust is asynchronous
dust.render('nicknameTemplate', data, function(err, out) {
  // The rendered output is in the out variable. Do with it what you will.
});

While this method works, it is not ideal for a production site. For the above example to work, you must include dust-full.js on your page, which is a much larger file than dust-core.js (because dust-full.js includes the parser and compiler, while dust-core.js only needs the runtime). Ideally, Dust templates are precompiled on the server and served to the client as JavaScript files.

HTML file:

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

And the JavaScript:

var data = {
  name: 'Green',
  nickname: 'Dust guy',
  showNickname: true
};
// The template is already loaded and registered, so all we need to do is render
dust.render('nicknameTemplate', data, function(err, out) {
  // The rendered output is in the out variable. Do with it what you will.
});