最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

templating - Javascript function in Nunjucks - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question asked Aug 10, 2018 at 13:52 Christophe SiroisChristophe Sirois 831 silver badge3 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

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
发布评论

评论列表(0)

  1. 暂无评论