Jinja2 : including multiple templates, and sharing variables between them

504 Views Asked by At

Fellow jinja2 lovers,

I'm migrating from a another templating language to jinja2. I want to convert my existing templates as much as possible without a change in the structure, but I'm running into some issues.

I have one parent file, which contains all the user input, and the main text to print. I have 4 files to include, that each contain some logic, and that "should" declare and assign values to variables based on that logic. Something like this :

  • parent (declares e, and uses a, b, c, d, and prints the output)
    • child1 (declares a, uses e)
    • child2 (declares b, uses a and e)
    • child3 (declares c, uses a, b e)
    • child4 (declares d, uses a, b, c, and e)

Now, thanks to the context passing, I can print in my child templates the values entered by the users (the "e"). The logic is applied properly, and inside the child, print shows that the variable ("a", "b", "c", or "d") is assigned to the right value. But once back to the parent template, jinja2 prints an empty string for these variables. The context isn't modified at all (I understand after much googling this is expected ?).

So I did the next logical thing (as the doc and google didn't help), I declared the variables ("a", "b", ...) inside the parent, but again, context isn't changed. Tried to append a value to the variables (now a list), still no joy.

So, is there any way for me to achieve this using jinja2 ? Been googling around, no joy.

Petzi

PS: maybe it is important to say that the parent file will be the child of another file, and so on ... my original templates are organized as an OOO tree

0

There are 0 best solutions below