[Fixed]-Divide Django base.html template into header, content and footer.html

18👍

Use include before using block header from header.html.

And you don’t need to create a block to include an HTML file into another.
In your header.html file, just write the code of header files.
Like this :

{% extends "admin/base_site.html" %}

     Header Html here...

And, In your base.html try this code :

{% include "templates/header.html" %}

    <body> body content </body>
    <footer> Footer Content </footer>

Note : Use include “templates/header.html” as per your location of header.html

3👍

There is something missing in your approach. Let’s see how the admin app loads a template:

  1. The user asks for a page, eg /admin/.
  2. The respective view in the admin app handles the request.
  3. The view renders the index.html template.
  4. This template extends the base.html template.

That’s all of it. When you replaced the base.html template and added the new block, django looks for this block definition in the index.html. Your new header file is nowhere to be involved in this process.

No matter what you do with your templates, django will always try to render the corresponding view’s template like the index.html (unless of course you change the views themselves). So you have the option to override any template starting from the last down to the first extend.

As Prakhar’s answer recommended, in order to make django acknowledge your new header template file, you need to use an include directive.

If this is not working, make sure that you use the correct path to both your base file and to your include file.

Please also take into account that includes are far more expensive performance-wise than extends or simple overrides.

👤Wtower

Leave a comment