passing a variable into a jinja import or include from a parent html file passing a variable into a jinja import or include from a parent html file flask flask

passing a variable into a jinja import or include from a parent html file


When you include a template into another one, it gains access to its context, so if you pass your person variable to mypage.html's context, you'll be able to access it from your imported template like this:

snippet.html:

<div id="item">    <ul>        <li>            <span>{{ person.name }}</span>            <span>{{ person.address }}</span>        </li>    </ul></div>

mypage.html:

<div id="result">    {% include 'snippet.html' %}</div>

view.py:

def view(person_id):    person = Person.get(person_id) # or whatever source you get your data from    return render_template('mypage.html', person=person)


This complements MatToufoutu's answer.

Environment globals are always available in macros, but context variables are not.To have the context available in an imported macro, you have to use with context when importing, e.g.:

{% from "your_macros.html" import your_macro with context %}