Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 899
Jay Avatar asked Dec 24 '11 12:12

Jay


People also ask

How do you set a variable in Jinja?

How do you assign values in Jinja? {{ }} tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code.

Can I use Jinja in HTML?

Jinja can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a specific extension: . html , . xml , or any other extension is just fine.

What is include in Jinja?

'Include' statement allows you to break large templates into smaller logical units that can then be assembled in the final template. When you use include you refer to another template and tell Jinja to render the referenced template. Jinja then inserts rendered text into the current template.

What is Jinja in HTML?

It was created by Armin Ronacher and is licensed under a BSD License. Jinja is similar to the Django template engine but provides Python-like expressions while ensuring that the templates are evaluated in a sandbox. It is a text-based template language and thus can be used to generate any markup as well as source code.


1 Answers

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)
like image 85
mdeous Avatar answered Sep 23 '22 16:09

mdeous