16

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" - this solution could be results from a search for customers for example

snippet.html

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

mypage.html

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

What is the best way to achieve this. In the documentation it talks about passing context around everywhere, but that seems to me to be a rather large object when rendering templates. surely it is easier to pass specific objects into each template?

Jay
  • 2,715
  • 8
  • 33
  • 33

2 Answers2

20

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)
mdeous
  • 17,513
  • 7
  • 56
  • 60
  • 1
    what about macros in included file – aWebDeveloper Sep 25 '13 at 10:17
  • 5
    The frustrating part of this is that you can't then make your small include generic enough to be agnostic to the "calling variable" name, so to speak. For instance, if I'm building a generic way to paginate some list of objects, I usually don't have them in an container called "objects", it's something more specific like "animals". – Dan Jan 12 '15 at 19:54
  • 1
    @Dan Why not use macros for that instead? – Achshar Jul 29 '17 at 13:41
7

This complements this answer by mdeous.

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 %}
dbc
  • 104,963
  • 20
  • 228
  • 340
kaka
  • 1,158
  • 1
  • 13
  • 15