4

I want to define and use a global helper function for the doT.js template engine how can I do this?

What I want to do is is something like this.

var xyz = function(p1, p2) { return p1 + p2; }

And use it in a doT.js template like this:

{{xyz(2,5)}}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
lhwparis
  • 230
  • 1
  • 9
  • 3
    @Connor if you declare your xyz as global with `window.xyz = function(p1, p2) { return p1 + p2; }` it should work in your template like in the example: `{{= xyz(2,5)}}` http://jsfiddle.net/52EXA/ – nemesv May 10 '14 at 13:17
  • @nemesv that's interesting to know, does it work for node? This bounty expires soon and there will be no answers, better yours than none aye? – iConnor May 14 '14 at 06:55
  • @Connor I haven't tried it with node, but I guess you can do there the same but use the `global` object instead of the `window` so `global.xyz = function(p1, p2) { return p1 + p2; }` altough this pollutes your global namespace, however if you want to have a real global helper you need to make it really global – nemesv May 14 '14 at 06:58
  • @nemesv doesn't doT prefix everything with `it`? – iConnor May 14 '14 at 06:59
  • @Connor no, you only need the `it` to access the currently passed in data object. But leaving the `it` out you can access any global object/function. – nemesv May 14 '14 at 07:29

1 Answers1

5

You can do so by using some of the advanced features of doT.js, see their advanced snippets examples for other advanced use.

This is how to defined a function to be used

{{##def.fntest = function() {
    return "Function test worked!";
}
#}}

And this execute it.

{{#def.fntest()}}
GillesC
  • 10,647
  • 3
  • 40
  • 55