Home > OS >  How to structure the templates folder in django and to use the extends
How to structure the templates folder in django and to use the extends

Time:07-14

I have a folder, templates, structured like below

/Users/AndyKw/Documents/Python/Else/Yes/templates

Within templates, I have two folders, admin and registration (see below for the tree)

templates (need.html)
|
|-- admin
|
|-- registration (base.html)

The file I use base.htmlis in the folder registration. It needs to use a file , need.html in the folder templates with the extends command.

Question is the following:

  • How do I configure in the settings.py the templates parameter to use registration as the main folder and through base.html to reach by using extends the file need.html in the templates folder?

One possible solution would be to invert the path, put need.html in the registration folder and put the base.html in the templates folder but the dev team seems to be quite unbending on this solution, this would be the less favourable way.

Any ideas/tips are welcomed.

CodePudding user response:

In settings.py:

TEMPLATES = [
    {
        'DIRS': [
            os.path.join(BASE_DIR, 'templates')
        ],
        ...
    }
]

Then in need.html:

<head>
  <!-- common headers for all templates -->
  {% block head %}
  {% endblock %}
</head>

<body>
  <!-- common body for all template -->
  {% block body %}
  {% endblock %}
</body>

Then in all your templates:

{% extends "need.html" %}

{% block head %}
<!-- headers here -->
{% endblock %}

{% block body %}
<!-- body here -->
{% endblock  %}

CodePudding user response:

I think you can do the following:

In the settings.py inside TEMPLATES change DIRS parameter to:

'DIRS': [os.path.join(BASE_DIR, 'templates/registration'), os.path.join(BASE_DIR, 'templates')],

This way you can use {% extends "need.html" %} inside registration/base.html.

Now, if you want to load all the base.html content below the extends then do the following:

  • base.html file:

    {% extends "need.html" %}
    
    {% block base_content %}
    
       <html content of base.html>
    
    {% endblock base_content %}
    
  • need.html file:

    <html content of need.html>
    {% block base_content %}{% endblock base_content %}
    
  • Related