在jinja2模板中选择一个单选钮

2024-05-19 22:26:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个jinja2模板和一个简单的用户首选项表单。首选项将作为python字典传递到render_template()函数中。根据设置,我需要将组中的一个单选按钮标记为选中。在

问:如何在不重复大量代码的情况下干净地完成它?在

以下是我目前的解决方案。它能工作,但很难看,而且有两个以上的单选按钮,很快就会变得很难管理。也许还有更好的办法。在

我使用两个字符串变量(用于2个无线基站)。根据首选项设置,其中一个将为空,另一个将设置为“选中”:

{% 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! -->

然后我在模板中使用这些字符串:

^{pr2}$

Tags: 函数字符串用户模板jinja2表单字典template
1条回答
网友
1楼 · 发布于 2024-05-19 22:26:56

我将索引检查和回溯检查的计算从模板转移到代码中。也可以使用字典解包,以便将较少的参数传递给render_template方法。在

do_index = user_prefs['when_done'] == 'index'
index_checked = 'checked' if do_index else ''
back_checked = '' if do_index else 'checked'

render_template('pages/something.html', form=some_form, index_checked=index_checked, back_checked=back_checked)

为了减少传递的参数数量,可以使用带解包的dict:

^{pr2}$

相关问题 更多 >