Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import / include assigned variables in Jinja2

In Jinja2, how can one access assigned variables (i.e. {% set X=Y %}) within files incorporated with include?

I'd expect the following to work given two Jinja2 files:

A.jinja:

Stuff
{% include 'B.jinja' -%}
B has {{ N }} references

B.jinja:

{% set N = 12 %}

I'd expect that A.jinja, when compiled with Jinja2, would produce the following output:

Stuff 
B has 12 references

However, it produces:

Stuff
B has  references

I'd be much obliged for any input as to how to access the Jinja2 variables, such as N above, in the file that includes the file where N is set.

Thank you for reading.

Brian

like image 817
Brian M. Hunt Avatar asked Jun 10 '10 19:06

Brian M. Hunt


1 Answers

There's a difference between include and import, although you should be able to do both.

  • include 'B.jinja simply renders the template and ignores any variable assignments or macros within it.
  • import 'B.jinja' as B, imports B as if it were a module, so you have to output B.N.
  • from 'B.jinja' import N imports variable N directly.

Change your import line to the last option and see if that fixes things. If you need more help, look at the documentation.

like image 149
Nikhil Avatar answered Sep 30 '22 22:09

Nikhil