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.
});