我正在使用Flask和jinja2的Mustache.js,在渲染图像时遇到了问题。
多亏了{% raw %}和{% endraw %},我成功地在jinja中渲染了我的胡子模板,但现在我需要在我的模板中使用Jinja中的url_for()来定义我的图像源。八字胡的{{}}和金家的之间有冲突。
我的javascript:
target = document.getElementById("target");
var template = $('#my-template').html();
Mustache.parse(template);
var rendered = Mustache.render(template, {"title":"My Title","photo_name":"photo.jpg"});
target.innerHTML = rendered;和我的模板:
<script id="my-template" type="x-tmpl-mustache">
{% raw %}
<h1> {{title}} </h1>
<img src="{{ url_for('static',filename='images/{{photo_name}}') }}" alt="my_photo">
{% endraw %}
</script>你知道怎么解决这个问题吗?
发布于 2019-06-20 22:50:38
您在相当多的内容上表达了raw处理,其中一些内容您实际上并不想成为原始内容。建议您缩小{% raw %} ... {% endraw %}的范围,使其仅涵盖您希望Mustache填充的那些模板变量。例如:
<script id="my-template" type="x-tmpl-mustache">
<h1> {% raw %}{{title}}{% endraw %} </h1>
<img src="{{ url_for('static',filename='images/')}}{% raw %}{{photo_name}}{% endraw %}" alt="my_photo">
</script>对于浏览器,这将呈现以下内容,然后可以使用JS /Mustache填充其模板部分:
<script id="my-template" type="x-tmpl-mustache">
<h1> {{title}} </h1>
<img src="/static/images/{{photo_name}}" alt="my_photo">
</script>通过这种方式,您可以让Mustache处理特定的模板替换,而Flask / Jinja2处理其余的内容。
使用两个具有交错和重叠职责的模板引擎-更不用说相同的模板变量标记语法-使得“引用”完全必要,但也非常无聊。
https://stackoverflow.com/questions/56688074
复制相似问题