【发布时间】:2017-05-08 21:51:51
【问题描述】:
我有一个带有简单用户偏好表单的 jinja2 模板。首选项作为 python 字典传递给 render_template() 函数。根据设置,我需要将组中的一个单选按钮标记为选中。
问:如何做到干净利落,没有太多的代码重复?
以下是我目前的解决方案。它可以工作,但它很丑,而且有两个以上的单选按钮,很快就会变得难以管理。可能有更好的方法。
我使用两个字符串变量(用于 2 个无线电 btns)。根据首选项设置,其中一个将为空,另一个将设置为“已选中”:
{% if user_prefs['when_done'] == 'index' %}
{% set indexchecked = 'checked' %}
{% set backchecked = '' %}
{% else %}
{% set indexchecked = '' %}
{% set backchecked = 'checked' %}
{% endif %}
<!-- With more radio buttons here, this would be a mess! -->
然后我在模板中使用这些字符串:
<form action="{{ url_for('prefs') }}" method="post">
<fieldset>
<div class="radio text-left">
<p><strong>After completing a task:</strong></p>
<label>
<input type="radio" name="when_done" value="index" {{ indexchecked }}>
Return to homepage
</label>
<br/>
<label>
<input type="radio" name="when_done" value="task" {{ taskchecked }}>
Go to next task
</label>
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Update preferences</button>
</div>
</fieldset>
</form>
【问题讨论】:
标签: python forms templates jinja2