Search code examples
nunjucks

How to lookup the current context in Nunjucks?


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.)


Solution

  • 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 }}