我想在视图中生成带有静态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})
Run Code Online (Sandbox Code Playgroud)
在模板中渲染它:
{{ image }}
Run Code Online (Sandbox Code Playgroud)
呈现img标记而不生成url:
<img src="{% static "brand.png" %} />
Run Code Online (Sandbox Code Playgroud)
您已将包含模板指令的字符串标记为安全.但是,模板一次性渲染.当你渲染那个字符串时,就是它,它不会通过然后呈现渲染字符串中的任何指令.您需要在不使用模板指令的情况下生成静态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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
559 次 |
| 最近记录: |