【问题标题】:Generate an image tag with a Django static url in the view instead of the template在视图而不是模板中生成带有 Django 静态 url 的图像标签
【发布时间】:2016-11-24 04:50:00
【问题描述】:

我想在视图中生成带有静态 url 的图像,然后在模板中呈现它。我使用mark_safe 这样HTML 就不会被转义。但是,它仍然不渲染图像。如何在 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})

在模板中渲染它:

{{ image }}

渲染img标签而不生成url:

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

【问题讨论】:

  • 为什么不在html部分调用静态文件?

标签: python django


【解决方案1】:

您已将包含模板指令的字符串标记为安全。但是,模板是一次性渲染的。当您渲染该字符串时,就是这样,它不会通过然后渲染渲染字符串中的任何指令。您需要 generate the static url 而不使用模板指令。

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

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

【讨论】:

    猜你喜欢
    • 2021-02-18
    • 2011-02-19
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 2011-02-09
    • 2015-01-08
    • 2012-03-11
    • 1970-01-01
    相关资源
    最近更新 更多