Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass selected, named arguments to Jinja2's include context?

Using Django templating engine I can include another partial template while setting a custom context using named arguments, like this:

{% include "list.html" with articles=articles_list1 only %} {% include "list.html" with articles=articles_list2 only %} 

As you may be supposing, articles_list1 and articles_list2 are two different lists, but I can reuse the very same list.html template which will be using the articles variable.

I'm trying to achieve the same thing using Jinja2, but I can't see what's the recommended way, as the with keyword is not supported.

like image 866
NiKo Avatar asked Feb 22 '12 23:02

NiKo


1 Answers

Jinja2 has an extension that enables the with keyword - it won't give you the same syntax as Django, and it may not work the way you anticipate but you could do this:

{% with articles=articles_list1 %}     {% include "list.html" %} {% endwith %} {% with articles=articles_list2 %}     {% include "list.html" %} {% endwith %} 

However, if list.html is basically just functioning as a way to create a list then you might want to change it to a macro instead - this will give you much more flexibility.

{% macro build_list(articles) %}     <ul>         {% for art in articles %}             <li>{{art}}</li>         {% endfor %}     </ul> {% endmacro %}  {# And you call it thusly #} {{ build_list(articles_list1) }} {{ build_list(articles_list2) }} 

To use this macro from another template, import it:

{% from "build_list_macro_def.html" import build_list %} 
like image 108
Sean Vieira Avatar answered Sep 22 '22 14:09

Sean Vieira