Access Flask context variables from included or imported Jade templates?

825 Views Asked by At

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?

1

There are 1 best solutions below

2
Syrus Akbary Nieto On BEST ANSWER

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