Search code examples
flaskpyjade

Access Flask context variables from included or imported Jade templates?


I'm using flask with pyjade for templating. I can access context variables within templates directly, and even in inherited templates, but not when I include mixins or try to import mixins from another template. Here's the example:

My Flask application serves this page:

def home():
    return render_template('index.jade', foo='bar')

So, foo is in the context now. Now let's say I have the following mixin in mixins.jade:

mixin m()
    div= foo

And in my template index.jade:

- from 'mixins.jade' import m

div= foo
+m()

In the template itself, I can read foo just fine, but in the imported mixin, I get

jinja2.exceptions.UndefinedError: 'foo' is undefined

Is this a shortcoming of pyjade, or is there a workaround?


Solution

  • this is not caused by pyjade but Jinja2...

    You have to import the template "with context". See Jinja2 docs

    This should work:

    - from 'mixins.jade' import m with context
    
    div= foo
    +m()