I'm trying to compile and render a Dust template on the fly with nested partials from the client, but I keep getting "Error: Template Not Found: [templatePath]". The example shown below works if I use a child template that doesn't reference any partials (e.g. /templates/includes/childTemplate.dust), but not from a higher level main template (e.g. /templates/main.dust). Is there a way to pre-compile high level templates with child partials included?
var model = { ... };
$.get('/templates/main.dust', function(tpl) {
var compiled = dust.compile(tpl, 'mainTemplate');
dust.loadSource(compiled);
dust.render('mainTemplate', model, function(err, output) {
if (err) {
console.log(err);
}
$('#target').html(output);
});
});
Dust partials are resolved at render time, not compile time, so there's no way to precompile into a master template.
Instead, Dust provides a way for you to tell it how to load additional templates through the use of the dust.onLoad
function.
dust.onLoad = function(templateName, callback) {
// naive jQuery loading of a new template
$.get('/templates/' + templateName + '.dust', function(data) {
callback(null, data);
});
};
If you need to compile the template after you receive it, pass it as the second parameter to callback
and Dust will compile it. If you're loading precompiled templates, just evaluate the precompiled template by calling dust.loadSource(data)
and then call callback()
.
You'll likely want to bake in a template precompilation step to your workflow, perhaps using the dustc
compiler that's included with Dust, so you don't have to compile on the client (it's slow, and you have to include dust-full.js
instead of dust-core.js
).
You might consider loading Dust and its templates as AMD modules. See http://www.dustjs.com/guides/setup/#amd . If you do this Dust will wire up the onLoad
for you automatically by using require
.
The Dust repo has some basic examples of different ways you can handle Dust in the browser. See examples/basic-browser and examples/amd.