问题
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