Performance: Macros for reusable components
This affects page load speed by reducing template parsing time and DOM complexity through reusable HTML snippets.
{% raw %}
{% macro card(title, description) %}
<div class="card">
<h2>{{ title }}</h2>
<p>{{ description }}</p>
</div>
{% endmacro %}
{{ card('Title 1', 'Description 1') }}
{{ card('Title 2', 'Description 2') }}
{% endraw %}{% raw %}
<!-- Repeating same HTML block multiple times -->
<div class="card">
<h2>{{ title }}</h2>
<p>{{ description }}</p>
</div>
<div class="card">
<h2>{{ title2 }}</h2>
<p>{{ description2 }}</p>
</div>
{% endraw %}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Repeated HTML blocks | More nodes due to duplication | Multiple reflows as DOM grows | Higher paint cost due to larger DOM | [X] Bad |
| Macros for reusable components | Fewer nodes, reused structure | Single reflow per component type | Lower paint cost with smaller DOM | [OK] Good |
{% macro %} in Flask templates?button that takes a parameter label?macros.html as:{% raw %}{% macro greet(name) %}Hello, {{ name }}!{% endmacro %}{% endraw %}index.html with:{% raw %}{% import 'macros.html' as m %}{% endraw %}{{ m.greet('Alice') }} in index.html?{% raw %}{% macro card(title) %}{{ title }}{% endmacro %}{% endraw %}
{{ card() }}Pass the test and this pattern moves unknown