Search code examples
node.jsexpressdust.js

DustJs - Access to different data


I'm using Dustjs and trying to compile, load, and render templates in 2 different ways : basically with the browser and Node (therefore in the client-side and server-side) for a single web page.

I tried something like that:
index.js file:

var      fs = require('fs');
var    path = require('path');
var express = require('express');
var    dust = require('dustjs-linkedin');

var app = express();

app.get('/', function(req, res) {

    res.writeHead(200, {"Content-Type": "text/html"});

    var src = fs.readFileSync(path.join(__dirname, 'hello.dust'), 'utf8'),
        compiled = dust.compile(src, 'hello');
    dust.loadSource(compiled);
    dust.render('hello', { world: "earth" }, function(err, out) {
      res.write(out);
    });

    res.end();
});
app.listen(80);

hello.dust file:

[...]

    Hello {world}!<br/>
    <p id="output"></p>

    <script type="text/javascript" src="js/dust-full.min.js"></script>
    <script type="text/dust" id="test">Hello {firstName}!</script>
    <script type="text/javascript">
        (function(){
            var src = document.getElementById('test').textContent,
                compiled = dust.compile(src, 'test');
            dust.loadSource(compiled);
            dust.render('test', { firstName: "John" }, function(err, out) {
              document.getElementById('output').textContent = out;
            });
        })();
    </script>

[...]

But here's what I get:

Hello earth!
Hello !

I did some research: The template "test" has no access to the given 'firstName', but still accesses 'world'.
I tried to set a context around 'firstName' and to access via {#test}, but it does not work.
I also tried to write the data in this way (it does not work either):

(function(){
    var context = dust.context(null, {"test": { "firstName": "John" }});
}())

I want to get this:

Hello earth!
Hello John!

Can someone explain to me I'm beginning in dust please?


Solution

  • The embedded template is getting processed by the server-- it can't tell that the template is inside a script tag.

    The real way to fix your issue is to decouple the JavaScript from your template instead of embedding it inline. If you must do this, however, you need to escape the embedded template.

    {` Hello {firstName}! `}
    

    This will cause the server to skip rendering what's inside the brackets, so that the client will be able to read the template.

    Again, though, you really should precompile the template instead.