有没有办法针对模板中的 Flask WTForms 错误简化此代码

Is there a way to simplify this code for Flask WTForms errors in template

这是我目前在 register.html 中的代码,有没有办法把这段代码放在更少的行中?

{% for error in reg_form.confirm_pass.errors %}
    <div class="ui tiny compact negative message">
        <p>{{ error }}</p>
    </div>
{% endfor %}
{% for error in reg_form.password.errors %}
    <div class="ui tiny compact negative message">
        <p>{{ error }}</p>
    </div>
{% endfor %}
{% for error in reg_form.errors['email'] %}
    <div class="ui tiny compact negative message">
        <p>{{ error }}</p>
    </div>
{% endfor %}

你可以定义一个macro:

Macros are comparable with functions in regular programming languages. They are useful to put often used idioms into reusable functions to not repeat yourself ("DRY").

该宏可以采用一个参数(要显示的 error 消息),您可以将它用于每种类型的错误,并在每种情况下传递要呈现的特定错误消息。

例如:

{% macro error_macro(error) %}
    <div class="ui tiny compact negative message">
        <p>{{ error }}</p>
    </div>
{% endmacro %}

{% for error in reg_form.confirm_pass.errors %}
    {{ error_macro(error) }}
{% endfor %}
{% for error in reg_form.password.errors %}
    {{ error_macro(error) }}
{% endfor %}
{% for error in reg_form.errors['email'] %}
    {{ error_macro(error) }}
{% endfor %}

这满足了您最初让代码更紧凑的要求,但更重要的是,如果您想更改错误的样式或格式,您只需更改一个地方的代码。