1

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.

d2uX
  • 241
  • 2
  • 14

1 Answers1

0

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.

Interrobang
  • 16,984
  • 3
  • 55
  • 63
  • Yeah also tried the global thing but didn't think of calling `dust.context`. Will try. Thanks for the quick reply. – d2uX Aug 27 '15 at 06:58
  • Since I just need the invocation count in the helper I used `dust.context(null, {numTimesCalled: 0}` so that it's hidden from the template (as far as I understood). Nevertheless the `context` solved my problem. Thanks again. – d2uX Aug 27 '15 at 07:33
  • Yes, the `options` (second argument) is hidden from the template and is exactly for scenarios like that. – Interrobang Aug 27 '15 at 16:01