« Back to home

DustJS share variables between client and server

Sharing variables between client and server is one of the most powerful features of NodeJS. However, it took me quite a bit of time to figure out how to do it properly with Dust templating engine (LinkedIn version).

Suppose that we want to share the product object below with the client Javascript:

app.get('/product/:id', function(req, res) {
  var product = store.getProduct(req.params.id);
  res.render('product', { product: product });
});

All you need to do is to put this in your product.dust file:

<script>var product = {product|s|js};</script>

The expression {product|s|js} means rendering the product object into JSON string without any escaping. The JSON string will be parsed back into normal Javascript object in the client script. s and js are 2 of the many filters LinkedIn Dust offers. You can get a list of all the available filters here.

Comments

comments powered by Disqus