Question

I'm trying to setup a filter which takes a string value and returns an image element, but I cannot make it to return the absolute one, just the relative one by hard-coding the url.

I would like to use something like:

return '<img src="{% static 'img/flags/country_flag.jpg'>"

Here is my code:

... extras.py

@register.filter(name="flag")
def flag(language):
    if language == 'fr':
        return '<img src="static/img/flags/french.jpg" class="flag">'
    elif language == 'ge':
        return '<img src="static/img/flags/german.jpg" class="flag">'

html

<td class="subtitle-flag"> {{subtitle.language | flag | safe}}</td>
Was it helpful?

Solution

Is it required for you to return the entire image object instead of just the name of the file? If it's not, you could try:

... extras.py

@register.filter(name="flag")
def flag(language):
    if language == 'fr':
        return 'french'
    elif language == 'ge':
        return 'german'

html

<td class="subtitle-flag">
    {% with flag_name=subtitle.language|flag|safe %}
    <img src="{% static 'img/flags/'|add:flag_name|add:'.jpg' %}" class="flag" />
    {% endwith %}
</td>

Read the docs for more information about the add filter and with tag.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top