在必填字段的标签上添加*

时间:2015-01-05 12:05:09

标签: python flask wtforms flask-wtforms

我想在标签的文本之前(或之后)添加'*',以防需要提交。

我现在可以在我的模板中使用它来执行此操作:

{% for field in form %}
    <label for="{{ field.name }}">
    {{ '*' if field.flags.required }}{{ field.label.text }} :
    </label>
    {{ field }}
{% endfor %}

有没有比这更好的方法,至少是一种避免手动添加标签元素的方法?

2 个答案:

答案 0 :(得分:2)

如果你这样做,没有比通过检查标志然后输出你想要的更简单的方法。但是,您可以更直接地更改标签的文本。你也可以制作一个宏,这样你就不需要为每个模板中的每个字段复制和粘贴那么多。创建模板&#34; forms.html&#34;:

{% macro form_field(field) %}
    {% if field.flags.required %}{{ field.label(text='*' + field.label.text) }}
    {% else %}{{ field.label }}{% endif %}:
    {{ field }}
{% endmacro %}

然后在其他模板中使用它:

{# 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 %}

答案 1 :(得分:0)

我试图为这个问题找到更好的答案,在我的例子中,这个 css 技巧效果很好,我不需要改变任何其他东西:

在-flask-wtf-project/app/static/styles/custom.css中添加一个文件

其中包含以下内容:

div.required label:after {
    content: " *";
    color: red;
}

然后确保将 base.html 中的 css(或所有使用表单的模板)包含在 {% block scripts %}

    <link rel="stylesheet" type="text/css" href="{{url_for('static',filename='styles/custom.css') }}">

我仍然认为自己是一个新手,所以如果这个提示以某种方式关闭,请加入。

只是我的 2 美分,我很满意,在这里或其他地方的任何其他线程上都找不到。

相关问题