如何在 Nunjucks 中查找当前上下文?

How to lookup the current context in Nunjucks?

在 Handlebars 中,您可以使用 this 查找当前上下文。

你如何在 Nunjucks 中做同样的事情?

例如,如果您想将整个上下文转储为 JSON 字符串:

<script>window.__config__ = {{ this | dump | safe }};</script>

(但this在Nunjucks中似乎不起作用。)

我不认为你的变量 this 在 nunjucks 模板上可用,但如果它是另一个你想检查的,你可以使用 dump 方法。

{{ users | dump }}

所以这将打印 json 对象,如果你有自动换行,它看起来真的很难看。

{{ users | dump | safe }}

这会很好用

或者:

env.addFilter('pprint', function(str, count) {
    return JSON.stringify(str, null, 4);
});

{{ users | pprint | safe }}

如果你需要context那么你可以添加全局函数

var env = nunjucks.configure([...
...
env.addGlobal('getContext', function() { 
    return this.ctx;
})

并将她的结果转储到模板中

{{ getContext() | dump| safe }}