Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide Django base.html template into header, content and footer.html

Hi I have extended Django Admin templates into my app/templates/admin directory.. in that directory I have base.html which contains

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

so I have created header.html which contains

{% extends "admin/base_site.html" %}
<!-- I also tried to include base.html here-->
{% block header %}
 Header Html here...
{% endblock %}

and replaced base.html to below content

{% block header %}  {% endblock %}
<body> body content </body>
<footer> Footer Content </footer>

but header content is not getting loaded.. so please suggest.

like image 563
Sanjay Avatar asked Jan 02 '17 07:01

Sanjay


2 Answers

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

like image 82
Prakhar Trivedi Avatar answered Oct 21 '22 15:10

Prakhar Trivedi


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.

like image 3
Wtower Avatar answered Oct 21 '22 17:10

Wtower