【发布时间】:2018-08-31 22:20:21
【问题描述】:
在我的 django 应用程序中,我试图从 JSON 变量中获取要加载的图像名称。在其 HTML 键中,有要显示的图像名称。 我正在读取该密钥并附加到静态路径中。但我收到此错误
TemplateSyntaxError at Could not parse the remainder
JSON
var json = [{
"html": "abc.jpg", //testing this failed
"col": 1,
"row": 1,
"size_y": 2,
"size_x": 2
}, {
"html": "def.jpg",
"col": 4,
"row": 1,
"size_y": 2,
"size_x": 2
},
{
"html": "bac.jpg",
"col": 6,
"row": 1,
"size_y": 2,
"size_x": 2
},
{
"html": "xyz.jpg",
"col": 1,
"row": 3,
"size_y": 1,
"size_x": 1
}, {
"html": "Brand.jpg",
"col": 4,
"row": 3,
"size_y": 1,
"size_x": 1
},
{
"html": "Brand.jpg",
"col": 6,
"row": 3,
"size_y": 1,
"size_x": 1
}
];
我的循环用于提取图像名称和其他所需参数
for(var index=0;index<json.length;index++) {
gridster.add_widget('<li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static \'images/'+json[index].html+'\' %}"></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row);
};
在这个循环中检查我得到的变量
var json = [{
"html": "abc.jpg", //testing this failed
"col": 1,
"row": 1,
"size_y": 2,
"size_x": 2
}, {
"html": "def.jpg",
"col": 4,
"row": 1,
"size_y": 2,
"size_x": 2
}, {
"html": "bac.jpg",
"col": 6,
"row": 1,
"size_y": 2,
"size_x": 2
}, {
"html": "xyz.jpg",
"col": 1,
"row": 3,
"size_y": 1,
"size_x": 1
}, {
"html": "Brand.jpg",
"col": 4,
"row": 3,
"size_y": 1,
"size_x": 1
}, {
"html": "Brand.jpg",
"col": 6,
"row": 3,
"size_y": 1,
"size_x": 1
}
];
for(var index=0;index<json.length;index++) {
console.log('<li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static \'images/'+json[index].html+'\' %}"></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row);
};
【问题讨论】:
-
{% static \'images/'+json[index].html+'\' %}- 你不能这样做 - 在你的浏览器运行 JavaScript 循环之前,模板会在服务器上呈现。 -
那么在这种情况下如何加载图像我想从与json中名称对应的服务器加载图像
-
如果在模板中定义了
json,你可以在那里使用static标签。或者您可能会发现最简单的方法是删除静态标签并硬编码前缀。 -
只是硬编码前缀作为放置服务器地址? 127.0.0.1:8000/static/images
http://127.0.0.1:8000/static/images -
是的,我就是这个意思。但是,您不需要域,
/static/images/可以。
标签: javascript python django django-templates jinja2