Search code examples
client-sidedust.jsprecompiled-templates

Dust.js - Render precompiled anonymous template on client side


Is there a way to render a precompiled template that has no name on the client side in DustJs?

Because documentation only shows with a name:

<!-- precompiled templates -->
<script type="text/javascript" src="/lib/templates.js"></script>
<script type="text/javascript">
// The templates are already registered, so we are ready to render!
dust.render('hello', { world: "Saturn" }, function(err, out) {
  document.getElementById('output').textContent = out;
})
</script>


EDIT : Ok it's probably too complicated to load a file, and I just noticed that when we compile without specifying name (in order to compile many template simultaneously), the path of the template is set as the default name. It is even editable with --pwd flag.
There is therefore always a name so the above function can operate.


Solution

  • It sounds like you would like to load templates by their path after they have been precompiled. Dust allows you to do this via AMD (require.js) compatibility.

    http://www.dustjs.com/guides/setup/#amd

    Once you've loaded require.js and set define.amd.dust = true, you can call dust.render with the path to a template and Dust will automatically load it for you.

    Note that this requires that you compile your templates with the --amd flag.

    <script src="r.js"></script>
    <script type="text/javascript">
        define.amd.dust = true;
        require(["lib/dust-full"], function(dust) {
            dust.render('path/to/your/template', function(err, out) { ... });
        });
    </script>
    

    The Dust repository has an example of using AMD to load templates.