0
votes

Doing some investigation for using dust.js, and I was wondering is there a way from preventing bad data to be rendered.

Template

Hello {name}! You have {count} new messages

Context

{
   "name": "Mick",
   "count": Math.PI
}

Yields, this result:

Hello Mick! You have 3.141592653589793 new messages

In this example, is there a way to escape the Math.PI, so that we can bail out and not print 3.14..

1
What do you want it to print instead? Why is Math.PI bad data? - smfoote

1 Answers

1
votes

You, as the developer, have to decide what is 'bad data' and what is an acceptable alternative.

Then you must either transform it in code (eg. the node.js building the page) before it reaches dust.js, or write a helper to render whatever you want with appropriate fallback. For instance, if you want to render integers, and display some custom fallback text otherwise, you might use a helper something like this:

Create an integerOrElse function, and save it in a file, eg.

local-dust-helpers.js:

// this extends dustjs-helpers (which must therefore be in package.json)
var dust = require('dustjs-helpers');

dust.helpers.integerOrElse = function (chunk, ctx, bodies, params) {
  // tap function resolves variables in params
  var value = dust.helpers.tap(params.value, chunk, ctx),
  fallback = dust.helpers.tap(params.fallback, chunk, ctx) || '';
  // define a fallback for the fallback :) ----------------^^^^^

  // for more brevity, you could do this in one line with a ternary operator
  if (!isNaN(value) && parseInt(value) == value) {
    return chunk.write(value);
  } else {
    return chunk.write(fallback);
  }
}

Then require() it in your app, replacing where you would have called the vanilla dust.js:

app.js

...
var dust  = require('./local-dust-helpers');
...

You can then use it just like a native dust.js directive:

template.dust

Hello {name}!
You have {@integerOrElse value='{count}' fallback='some' /} new messages