Bottlepy/Flask - 如何设置复选框?

Bottlepy/Flask - How to set a checkbox?

我正在尝试设置一个复选框,如果它在过去的模板中被选中的话。 换句话说,如果用户选中复选框并单击提交按钮,他应该能够看到他选中了哪些选项。 我的代码是这样的:

if request.GET.get('submit', '').strip():
    checkbox = request.GET.get('box1')
    return template('my_template.j2', box1 = checkbox)

我该怎么做?

在您的模板文件中,您可以添加以下内容:

<input type="checkbox" name="box1" value="box1" {{'checked="checked"' if box1 else ""}}/>

您可以使用花括号内传入模板的 python 对象,您可以在 documentation for inline expressions.

中找到更多信息

这也有效:

<input type="checkbox" name="box1" value="box1" {{ "checked" if box1 else "" }}/>