Performance: Control structures (if, for)
Control structures in Flask templates affect how much HTML is generated and how fast the page renders.
{% for item in active_items %}
<div class="active">{{ item.name }}</div>
{% endfor %}
{% for item in inactive_items %}
<div>{{ item.name }}</div>
{% endfor %}{% for item in items %}
{% if item.is_active %}
<div class="active">{{ item.name }}</div>
{% else %}
<div>{{ item.name }}</div>
{% endif %}
{% endfor %}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Complex if inside for loop | Many conditional checks per item | Multiple reflows if DOM changes dynamically | Higher paint cost due to larger HTML | [X] Bad |
| Separate loops with filtered data | No conditional checks | Stable DOM structure | Lower paint cost with simpler HTML | [OK] Good |
{% if %} statement do in a Flask template?{% if %}{% if %} statement checks a condition and controls whether some HTML is shown.{% for %} repeats HTML, functions and imports are not done with {% if %}.{% if %} controls conditional display [OK]{% for variable in iterable %}.{% for color in ['red', 'green', 'blue'] %}
{{ color }}
{% endfor %}{% for user in users %}
{{ user.name }}
{% endfor %}users is an empty list, what happens?users is empty, the for loop body does not execute at all.items is empty, otherwise list each item inside <li> tags within a <ul></ul>. Which Flask template code correctly does this?No items found
{% endif %} uses{% if items %} which is true if list is not empty.No items found
{% endif %} correctly uses{% else %} to show "No items found" if empty.Pass the test and this pattern moves unknown