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


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

Answers 2
Added at 2017-01-02 08:01

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

<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.

Answers to

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

nr: #1 dodano: 2017-01-02 08:01

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

nr: #2 dodano: 2017-01-02 10:01

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.

Source Show
◀ Wstecz