Performance: Error message display in templates
This affects page load speed and interaction responsiveness by how error messages are rendered and updated in the DOM.
return render_template('form.html', errors=errors) # errors only contains current relevant errors <!-- In template --> {% for field, msgs in errors.items() if msgs %} <div class="error">{{ field }}: {{ msgs|join(", ") }}</div> {% endfor %}
return render_template('form.html', errors=errors) # errors is a large dict with all possible errors <!-- In template --> {% for field, msgs in errors.items() %} <div class="error">{{ field }}: {{ msgs|join(", ") }}</div> {% endfor %}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Render all possible errors regardless of presence | Many nodes created | Multiple reflows | High paint cost | [X] Bad |
| Render only current errors present | Minimal nodes created | Single reflow | Low paint cost | [OK] Good |
{% if %} statements to conditionally render content.{% if error %} to check if the error variable has a value before showing it.error inside a Flask template?{{ variable }}.error, use {{ error }}.{% if errors %}
{{ errors[0] }}
{% endif %}errors is a list: ["Invalid email"], what will be rendered?errors contains one item, so it is truthy and the block runs.{{ errors[0] }} which is "Invalid email" inside a div with class "error".{% if error %}
{{ error }}
{% endif %}error='Invalid input' from Flask. What is the likely problem?error but the template uses a different variable name or none, the condition fails.error to display the message correctly.errors with accessible markup?{% if errors %} ensures the list is not empty before rendering.{% for %} and use accessible markup<ul> with aria-live="polite" for screen readers.Pass the test and this pattern moves unknown