【发布时间】:2018-12-15 13:34:39
【问题描述】:
如果我在 .html 模板中呈现静态图像,它就可以工作。但是,如果我将静态标记字符串作为字典值提供给模板(上下文),它将不起作用。这似乎与字符串格式有关,不允许我以我需要的方式使用 {% %} 。我试过了:
1. .format()
2. 百分号转义
3. 原始字符串
4. 串联
5. 自动转义
6. |安全
还有一些其他的东西
基本上,我在view.py中用'''{% %}'''构造一个多行字符串,然后用这个字符串作为上下文渲染一个模板。 Python 2.
更新
简单的非工作示例:
view.py
def index(request):
image_insert = ''
images = ['image1.jpg', 'image2.jpg', 'image3.jpg']
for image in images:
image_insert += '<img src="{}">'.format(image)
context = {'insert': image_insert}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
First Image
<img src={% static "image.jpg" %}>
Second Image <!-- does not work -->
{{ image_insert | safe }}
</body>
</html>
页面来源:
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
<img src=/static/mqdefault.jpg>
Second Image
<img src="image1.jpg"><img src="image2.jpg"><img src="image3.jpg">
</body>
</html>
显然是有区别的。这是 Django 1.11 顺便说一句,如果它有所作为。
【问题讨论】:
-
能否请您也发布您的模板?
-
@mrehan 更新
标签: python django python-2.7 django-templates