Issue
This is my current code in register.html
, is there a way to put this code in less lines?
{% 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 %}
Solution
You can define a 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").
The macro can take one argument (the error
message to display) and you can use it for each type of error you have, passing the specific error message to be rendered in each case.
For example:
{% 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 %}
This satisfies your original requirement of making the code more compact, but more importantly it means you only have to change the code in one place if you want to change the style or format of the errors.
Answered By – costaparas
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0