Block tag inside url_for() in Jinja2
<p>I'm using Jinja2 to render my frontend (and python is on the backend). Each page will have a different image on its top, like this:</p>

<pre><code>&lt;header&gt;
    &lt;img src="static/img/pic1.png"&gt;
&lt;/header&gt;
</code></pre>

<p>I used <em>url_for()</em> to get the correct path of my static folder:</p>

<pre><code>&lt;header&gt;
    &lt;img src="{{ url_for('static', filename='img/pic1.png') }}"&gt; 
&lt;/header&gt;
</code></pre>

<p>So far, so good. But I would like to put a block inside the filename parameter, so I can reuse the code and only overwrite the name of the image. This is what I'm trying:</p>

<pre><code>&lt;header&gt;
    &lt;img src="{{ url_for('static', filename='{% block img %}img/pic1.png{% endblock %}') }}"&gt;
&lt;/header&gt;
</code></pre>

<p>But it doesn't work, this is the final code that is rendered by Jinja2:</p>

<pre><code>&lt;header&gt;
    &lt;img src="/static/%7B%25%20block%20img%20%25%7Dimg/pic1.png%7B%25%20endblock%20%25%7D"&gt;
&lt;/header&gt;
</code></pre>

<p>As you can see, Jinja2 doesn't recognize the <em>block</em> tag as an expression and treats it as a string. If it worked, I would be able to set the picture of each page only using this code:</p>

<pre><code>{% extends "base.html" %}
{% block img %}img/pic2.png{% endblock %}
...
</code></pre>

<p>Could someone help, please? By the way, <a href="http://stackoverflow.com/questions/32024551/reference-template-variable-within-jinja-expression">this</a> post didn't help me.</p>

<p>What you need is a <strong>macro</strong> to define a kind of function in your template. See this topic in 
<a href="http://jinja.pocoo.org/docs/dev/templates/" rel="nofollow">http://jinja.pocoo.org/docs/dev/templates/</a></p>

<pre><code>{% macro header_img(name) -%}
    &lt;img src="{{ url_for('static', filename=name) }}"&gt;
{%- endmacro %}
</code></pre>

<p>You can put this macro in an util template and <a href="http://jinja.pocoo.org/docs/dev/templates/#import" rel="nofollow">import</a> it in each page.</p>

<p>Use the syntax:</p>

<pre><code>&lt;header&gt;{{ header_img("your_image.jpg") }}&lt;/header&gt;
</code></pre>

python frontend jinja2