Search code examples
javascripttemplatingnunjucks

Javascript function in Nunjucks


So I've found this in the Nunjucks docs:

Function Calls

If you have passed a javascript method to your template, you can call it like normal.

{{ foo(1, 2, 3) }}

But I can't seem to make in work, I've tried putting my function on the html page in <script> tags but its not working.

I've also tried passing it with the data to the render function:

{
    stuff: function (string, length) {
        while (string < length) {
            string = "0" + string
        }
    }
}

And I get: unable to call data["stuff"], which is undefined of falsey


Solution

  • You can use addGlobal (see g) or pass a function to render (see f).

    var nunjucks  = require('nunjucks');
    var env = nunjucks.configure();
    
    function f (s) {
        return s + s; 
    }
    
    function g (s) {
        return s + s + s; 
    }
    
    env.addGlobal('g', g);
    
    var res = nunjucks.renderString('{{f("OK")}} {{g("ok")}}', {f: f});    
    console.log(res);
    
    //Output: OKOK okokok