Search code examples
javascriptdust.jsdust-helpers

Dust.js get call count of helper in template


So I have a dust.js helper which requires some jsx module when called and afterwards renders this module as html (some kind of plugin).

{@react type="Text"\}
...
<some Markup>
...
{@react type="Text"\}
{@react type="Text"\}

Meanwhile I have a data structure which contains all the elements that should be rendered on this template (a page)

['1st', '2nd', '3rd']

In my helper I'd like to know how often I called @react. Like incrementing a counter on the context which all helpers called within this template can access.

I was fiddeling around with context.pop() and context.push but wasn't able to mutate the template's context. Every helper gets it's own. So I either need a way to get the call count of the helper or store the current number of invocations of the helper somewhere accessible to the other ones.

However, when doing sth like {@react type="Text" index=0\} and afterwards accessing it with context.get(['page', 'elements', params.index]) it works (of course). But this enforces me to keep count of the elements I am disposing (especially annoying when adding and removing elements)

Hope s/o has an idea, maybe I'm just missing sth really simple. Cheers.


Solution

  • There is a special global object attached to each Context that contains references you'd like to be available everywhere in your template.

    For more information, see Context Globals.

    You prepopulate the global by calling dust.context({ foo: 'bar' }) to create a Context object. You can pass this to Dust in your render step instead of a plain Object.

    Inside any helper, you can access the global directly to set properties on it:

    react: function(chunk, context, bodies, params) {
      var numTimesCalled = ++context.global.numTimesCalled;
    });
    

    You can use properties in the global in your template. You can think of them as being at the "lowest" level in the context stack.