How to lookup the current context in Nunjucks?

一笑奈何 提交于 2019-12-24 07:17:22

问题


In Handlebars you can use this to look up the current context.

How do you do the same in Nunjucks?

For example, if you wanted to dump the entire context as a JSON string:

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

(But this doesn't seem to work in Nunjucks.)


回答1:


If you need context then you can add global function

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

And dump her result in template

{{ getContext() | dump| safe }}



回答2:


I don't think you the variable this is available on a nunjucks template, but if it's another you wish to inspect you can use the dump method.

{{ users | dump }}

So that will print the json object, which looks really ugly if you have autoscape on.

{{ users | dump | safe }}

this will work just fine

ALTERNATIVELY:

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

{{ users | pprint | safe }}



来源:https://stackoverflow.com/questions/38726828/how-to-lookup-the-current-context-in-nunjucks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!