Search code examples
dust.js

Uncompiled partials in dust.js


I'm trying to figure out how to include an uncompiled dust partial in a dust view.

main.dust:

<div class="container">
    {>"toolbar"/}

</div>

toolbar.dust:

<div class="row">
    toolbar
    {somevariable}
</div>

This attempts to load a compiled partial named toolbar.js not the uncompiled toolbar.dust template?

I found this post on here: How do you include a raw, uncompiled partial in dust.js? which will let me load files but any {variables} they contain are not replaced.

I don't want to have to compile views every time I change them. How can I include an uncompiled template with its variables replaced?


Solution

  • You can add an onLoad handler to Dust to tell it how it should try to load partials. By default, Dust expects you to have pre-registered all templates you're going to try to use.

    More info: Loading Templates (it sounds like you want to load Uncompiled Templates)

    Note: you shouldn't really do this in production, because compiling templates is much slower than rendering them. If you're using something like Express, take time to set up a build step or an Express plugin to compile for you. There are examples in the examples directory on the Dust GitHub repository.

    An onLoad handler might look something like this (assuming you're running Dust on the server-- the idea is the same for the client):

    dust.onLoad = function(templateName, callback) {
      fs.readFile(templateName + '.dust', { encoding: 'utf8' }, function(err, data) {
        callback(null, data);
      });
    };
    

    Notice that callback uses the Node errback signature, so you can simplify this code to:

    dust.onLoad = function(templateName, callback) {
      fs.readFile(templateName + '.dust', { encoding: 'utf8' }, callback);
    };
    

    There is an example on our GitHub repo that does basically this.