Search code examples
dust.js

dust.js turn off HTML encoding globally


Is there a way to turn off HTML encoding globally within dust.js? I trust my data enough to want to turn it off during rendering. Instead of having to add "|s" to every tag in every template file, being able to set it globally would be ideal.

If not, is there a way to use filtering with custom helpers? I created a @val helper, but have no way to apply the "|s" filter. According to the docs, the following should work:

{@val filters="|s" /}

But it doesn't work on its own, so I'm thinking some logic needs to be placed within the helper itself.


Solution

  • You can use the little-documented esc pragma to apply a global context to a template block.

    {
      "hello": "Hello & World"
    }
    
    {%esc:s}
      This applies |s to everything inside the pragma
      {hello} <-- will not escape the ampersand
    {/esc}
    

    For your second question, it depends on what your helper is doing. If your helper returns any sort of Chunk, via Chunk.render for example, you must apply filters manually. If your helper returns a value, that value will be passed through any filters that are present. Here are a couple examples: say you have a helper {@val} that simply returns anything passed to it as a value.

    Returning a value from your helper means filters is respected:

    dust.helpers.val = function(chunk, context, bodies, params) {
      return params.value;
    };
    
    {@val value="Hello & World" /} <-- Hello &amp; World
    {@val value="Hello & World" filters="s" /} <-- Hello & World
    

    Returning a chunk from your helper ignores filters:

    dust.helpers.val = function(chunk, context, bodies, params) {
      return chunk.write(params.value);
    };
    
    {@val value="Hello & World" /} <-- Hello & World