简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM