shuboy2014
shuboy2014

Reputation: 1370

Generate an image tag with a Django static url in the view instead of the template

I want to generate an image with a static url in a view, then render it in a template. I use mark_safe so that the HTML won't be escaped. However, it still doesn't render the image. How do I generate the image tag in Python?

from django.shortcuts import render
from django.utils.safestring import mark_safe

def check(request):
    html = mark_safe('<img src="{% static "brand.png" %}" />')
    return render(request, "check.html", {"image": html})

Rendering it in a template:

{{ image }}

renders the img tag without generating the url:

<img src="{% static "brand.png" %} />

Upvotes: 2

Views: 1253

Answers (1)

davidism
davidism

Reputation: 127180

You've marked the string, containing a template directive, as safe. However, templates are rendered in one pass. When you render that string, that's it, it doesn't go through and then render any directives that were in rendered strings. You need to generate the static url without using template directives.

from django.contrib.staticfiles.templatetags.staticfiles import static

url = static('images/deal/deal-brand.png')
img = mark_safe('<img src="{url}">'.format(url=url))

Upvotes: 8

Related Questions