1

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.
Cinn
  • 4,281
  • 2
  • 20
  • 32

1 Answers1

2

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.

Interrobang
  • 16,984
  • 3
  • 55
  • 63
  • Thank you, I'll consider using require.js. But it is possible to load templates by their path without AMD: ` ` – Cinn Jul 24 '15 at 18:57
  • You could write your own custom script injection that works through `dust.onLoad`. But you have to load the script somehow, whether it's via `jQuery.getScript`, require.js, or something else. Dust is not a script loader. – Interrobang Jul 24 '15 at 19:09
  • For example, a really naïve method might look like `dust.onLoad = function(path, cb) { $.getScript('/templates/' + path).then(cb); }`. That's a loader that doesn't use AMD but uses jQuery instead. But you have to write those yourself. The docs explain onLoad: http://www.dustjs.com/guides/onload/ – Interrobang Jul 24 '15 at 20:58