flask jinja macros variable in url_for


Question

I have a flask app with a jinja macro that looks like that

{% macro icon(site, title="") %}
    <img src="{{ url_for('static', filename="icons/XXX.png") }}" alt="{{ title }}" class="img-icon">
{% endmacro %}

What I need to do is have the filename equals to the site variable passed to the macro. so instead of the XXX it should have the value of site.

Is there a way to do that?

1
3
10/25/2012 2:50:31 PM

Accepted Answer

This should work:

{% macro icon(site, title="") %}
    <img src="{{ url_for('static', filename='icons/%s.png' % site) }}" alt="{{ title }}" class="img-icon">
{% endmacro %}
9
10/25/2012 2:56:38 PM

Recommended way of string formatting in python ever since 2.6 (pep-3101) is to use str.format():

{% macro icon(site, title="") %}
    <img src="{{ url_for('static', filename='icons/{0}.png'.format(site)) }}" alt="{{ title }}" class="img-icon">
{% endmacro %}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon