Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterized reusable blocks with Jinja2 (Flask) templating engine

In Jinja2 templating engine (using Flask), I want to achieve something like that:

{% reusable_block avatar(user) %}
     <img src='{{ user.avatar }}' title='{{ user.name }}'/> 
{% reusable_block %}

and then in various places:

{% for u in users %}
    {% call avatar(u) %}
{% endfor %}

However I can't find such a feature (I made up reusable_blocks for this question) in Jinja documentation. What I need is basically reusable blocks that can take parameters. Any ideas know how can I do that with Jinja2?

like image 670
ahmet alp balkan Avatar asked Feb 27 '13 07:02

ahmet alp balkan


1 Answers

You can use macros.

{% macro input(name, value='', type='text', size=20) -%}
    <input type="{{ type }}" name="{{ name }}" value="{{value|e }}" size="{{ size }}">
{%- endmacro %}


<p>{{ input('username') }}</p>
<p>{{ input('password', type='password') }}</p>

More documentation here.

like image 69
Lütfi Demirci Avatar answered Sep 25 '22 00:09

Lütfi Demirci