Jinja2 : Variable call impossible within markdown from two disticnt template using jinja2

394 Views Asked by At

I am using jinj2 inside markdown files to create a documentation template via Mkdocs.

The whole process is created through a pipeline so I get to see what is done by the jinja2 code I write inside my templates, but there is that one particular problem that is blocking me right now:

let's say that I have template1.md and template2.md and one var file that is called file2.yml

the vars that are inside file2.yml are the cars that are included in the template2.yml and its content is similar to this :

squads:
  
  - name: squad_name
    mail: [email protected]
    env_responsiblity: test

on template2.md and after the processing of the jinja2 command the fields are correctly filled so that's ok so far.

what I want is to call the env_responsibility value inside my second template1.md like this :

{% import 'template2.md' as t %}

#{{environement}}

##Responsibility

{% if environement = t.env_responsibility %}

The environement {{environement}} is under the responsability of the {{t.squad.name}}

{% endif }%

the sure thing is that the call of squad name and env_responsibility is not working but I have no error that could point what is wrong.

Could someone please help to highlight the issue?

2

There are 2 best solutions below

2
On

It is not possible to import the variables inserted into a template, since these are only available when the template is rendered and is not saved in the context afterwards. The variables that you can import from one template into another, are the variables written in jinja. E.g.

Template_1

{{ rendered_variable }}
{% set jinja_variable = "Something" %}

Template_2

{% import "template_1" as t %}

This does not work: {{ t.rendered_variable }}
This works: {{ t.jinja_variable }}

You will need to provide the second template with the values you need from the first template, there is no way around it, when they values are not known before rendering.

0
On

If you need to have the context of your first template available while it's used in the second you can try including instead of importing.

https://jinja.palletsprojects.com/en/2.11.x/templates/#import-visibility

On another note it seems you may try to put the contents of your yml into your rendering context before rendering anything like Alexander already said. That way you have the data available in all your templates.