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

前端 未结 2 616
陌清茗
陌清茗 2021-02-07 14:41

The scenario would be:

\"you have a variable called person which contains a number of fields like name, address, etc which you want to pass to a partial piece of html\"

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 15:14

    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:

    • {{ person.name }} {{ person.address }}

    mypage.html:

    {% include 'snippet.html' %}

    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)
    

提交回复
热议问题