【发布时间】:2021-02-02 11:49:07
【问题描述】:
我正在创建一个简单的 html 问卷文档,作为基本模板,我使用以下 jinja 代码:
from jinja2 import Template
title = ['1 title', '2 title']
message = ['1 message', '2 message']
template = Template(
"""
{% macro create_block(title, message) %}
<h1> {{title}} </h1>
<h3>question?</h3>
<input type="radio" value="val1" name="question1_{{ i }}">option A</input>
<input type="radio" value="val2" name="question1_{{ i }}">option B</input>
<h3>question 2?</h3>
<input type="radio" value="one" name="question1_{{ i }}">a</input>
<input type="radio" value="two" name="question1_{{ i }}">b</input>
<input type="radio" value="three" name="question1_{{ i }}">c</input>
{% endmacro %}
{% for title, message in list %}
{{ create_block(title, message) }}
{% endfor %}
""")
print_html(template.render(list=zip(title, message)))
上面的模板为标题和消息列表中的元素数量创建了问题集。比如title中的两个元素,上面的代码会生成两个不同的问卷集。但是,为了生成有效的 html 文档,我想更改 name="question1_{{ i }} 中的 {{i}} 参数。对于上述模板,预期的输出如下所示:
<h1>
1 title
</h1>
<h3>
question?
</h3>
<input name="question1_1" type="radio" value="val1"/>
option A
<input name="question1_1" type="radio" value="val2"/>
option B
<h3>
question 2?
</h3>
<input name="question1_2" type="radio" value="one"/>
a
<input name="question1_2" type="radio" value="two"/>
b
<input name="question1_2" type="radio" value="three"/>
c
<h1>
2 title
</h1>
<h3>
question?
</h3>
<input name="question2_1" type="radio" value="val1"/>
option A
<input name="question2_1" type="radio" value="val2"/>
option B
<h3>
question 2?
</h3>
<input name="question2_2" type="radio" value="one"/>
a
<input name="question2_2" type="radio" value="two"/>
b
<input name="question2_2" type="radio" value="three"/>
c
在 Jinja 中,获得上述输出且复选框名称不同的正确方法是什么?
【问题讨论】:
-
我尝试
{% for i in title %} {% endfor %}。但是,由于某种原因,它将“title”作为字符串,而不是列表对象。知道如何解决这个问题吗?
标签: python html python-3.x flask jinja2