Javascript function in Nunjucks
Asked Answered
S

1

8

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

Strychninism answered 10/8, 2018 at 13:52 Comment(0)
G
12

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
Garbo answered 11/8, 2018 at 8:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.