Search code examples
djangodjango-templatesdjango-template-filters

add static ressource to template filter function


I want to dynamically add icons from my static dir when using a template tag, but I do not want to add them in the templates HTML, but using a filter:

{% for field in form %}
        <td>{{ field|format_ }}</td>
{% endfor %}

and format_ looking like this:

@register.filter(name = "format_")
def format_(field):
    if field.widget_type == "clearablefile":
        f = f"""{field}<button class="btn btn-danger"><img src="{{% static 'images/x-square.svg' %}}"></button>"""
        return mark_safe(f)
    return field

I tried it with the same syntax I would use in the template, but just escaped: <img src="{{% static 'images/x-square.svg' %}}"> which just shows exactly that in clear text, not the icon on the template. What is the correct way here?


Solution

  • Use static function like this:

    # Older Django <3.0 (also deprecated in 2.0):
    from django.contrib.staticfiles.templatetags.staticfiles import static
    
    # Django 3.0+
    from django.templatetags.static import static
    
    iconUrl = static('images/x-square.svg')
    

    Your code will be:

    @register.filter(name = "format_")
    def format_(field):
        if field.widget_type == "clearablefile":
            iconUrl = static('images/x-square.svg')
            f = f"""{field}<button class="btn btn-danger"><img src="{iconUrl}"></button>"""
            return mark_safe(f)
        return field