Django Use of {% extends %} , {% include %} and {% blocks %}


Example

summary

  • {% extends %}: this declares the template given as an argument as the current template's parent. Usage: {% extends 'parent_template.html' %}.

  • {% block %}{% endblock %}: This is used to define sections in your templates, so that if another template extends this one, it'll be able to replace whatever html code has been written inside of it. Blocks are identified by their name. Usage: {% block content %} <html_code> {% endblock %}.

  • {% include %}: this will insert a template within the current one. Be aware that the included template will receive the request's context, and you can give it custom variables too. Basic usage: {% include 'template_name.html' %}, usage with variables: {% include 'template_name.html' with variable='value' variable2=8 %}

Guide

Suppose you are building up your front end side code with having common layouts for all code and you do not want to repeat the code for every template. Django gives you in built tags for doing so.
Suppose we have one blog website having 3 templates which share the same layout:

project_directory
    ..
    templates
      front-page.html
      blogs.html
      blog-detail.html

1 ) Define base.html file,

<html>
  <head>
  </head>

  <body>
        {% block content %}
        {% endblock %}
   </body>
</html>

2 ) Extend it in blog.html like,

{% extends 'base.html' %}

{% block content %}
    # write your blog related code here
{% endblock %}

# None of the code written here will be added to the template

Here we extended the base layout so its HTML layout is now available in the blog.html file.The concept of { % block %} is template inheritance which allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.

3 ) Now suppose all of your 3 templates also having same HTML div which defines some popular posts.Instead of being written the 3 times create one new template posts.html.

blog.html

{% extends 'base.html' %}

{% block content %}
    # write your blog related code here
    {% include 'posts.html' %} # includes posts.html in blog.html file without passing any data
    <!-- or -->
    {% include 'posts.html' with posts=postdata %} # includes posts.html in blog.html file with passing posts data which is context of view function returns.
{% endblock %}