0
0
Djangoframework~8 mins

Template inheritance with base template in Django - Performance & Optimization

Choose your learning style9 modes available
Performance: Template inheritance with base template
MEDIUM IMPACT
This affects the server-side rendering speed, impacting the initial page load time.
Reusing common layout across multiple pages
Django
{% comment %}Base template with blocks{% endcomment %}
<!-- base.html -->
<html>
<head><title>{% block title %}Default Title{% endblock %}</title></head>
<body>
<header>Site header</header>
<main>{% block content %}{% endblock %}</main>
<footer>Site footer</footer>
</body>
</html>

{% comment %}Child template{% endcomment %}
{% extends "base.html" %}
{% block title %}Page 1{% endblock %}
{% block content %}Content for page 1{% endblock %}
Template inheritance avoids repeating HTML, so server compiles less code.
📈 Performance GainReduces server template parsing time, improving LCP.
Reusing common layout across multiple pages
Django
{% comment %}Each page repeats full HTML structure{% endcomment %}
<html>
<head><title>Page 1</title></head>
<body>
<header>Site header</header>
<main>Content for page 1</main>
<footer>Site footer</footer>
</body>
</html>
Repeating full HTML structure in every template causes larger template files and more server processing.
📉 Performance CostIncreases server template parsing time, slowing LCP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Repeated full HTML in each templateNo change (server-side)No change (browser)Larger templates increase server parsing time[X] Bad
Template inheritance with base templateNo change (server-side)No change (browser)Smaller templates reduce server parsing time[OK] Good
Rendering Pipeline
Template inheritance is resolved on the server before HTML is sent. The browser receives a single combined HTML document.
Server Template Rendering
⚠️ BottleneckServer Template Rendering can be slower if templates are large and duplicated.
Core Web Vital Affected
LCP
This affects the server-side rendering speed, impacting the initial page load time.
Optimization Tips
1Use base templates to avoid repeating full HTML in every page.
2Define blocks for variable content to keep templates small and reusable.
3Efficient server rendering from inheritance improves loading speed.
Performance Quiz - 3 Questions
Test your performance knowledge
How does template inheritance affect the size of the HTML sent to the browser?
AIt increases HTML size by adding extra tags
BIt has no effect on HTML size
CIt reduces HTML size by avoiding repeated code
DIt duplicates HTML for each block
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, and inspect the HTML document size and load time.
What to look for: Faster document load time indicates good template inheritance usage.