Tax*_*ool 1 python flask wtforms flask-wtforms
我想在标签文本之前(或之后)添加“*”,以防需要提交。
我现在可以通过在我的模板中使用它来做到这一点:
{% for field in form %}
<label for="{{ field.name }}">
{{ '*' if field.flags.required }}{{ field.label.text }} :
</label>
{{ field }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
有没有比这更好的方法,至少有一种方法可以避免手动添加标签元素?
这就是你如何做到的,没有比检查标志然后输出你想要的内容更简单的方法了。不过,您可以更直接地更改标签的文本。您还可以用它创建一个宏,这样您就不需要为每个模板中的每个字段复制和粘贴太多内容。创建模板“forms.html”:
{% macro form_field(field) %}
{% if field.flags.required %}{{ field.label(text='*' + field.label.text) }}
{% else %}{{ field.label }}{% endif %}:
{{ field }}
{% endmacro %}
Run Code Online (Sandbox Code Playgroud)
然后在其他模板中使用它:
{# import the macro at the top of the template #}
{% from "forms.html" import form_field %}
{# use it in your for loop #}
{% for field in form %}
{{ form_field(field) }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)