How to have nested base.html in django's templates?

时间:2017-08-05 10:58:59

标签: django django-templates

I am rebuilding all my templates so it becomes a lot more manageable and custom, the tree would look like this :

├───core
│   └───templates
│       └───base.html (original, touches every page)
│   ...   
│
├───app1
│   └───templates
│       ├───base.html (extends from core/base.html, only touches app1)
│       └───file1.html (extends from app1/base.html)
│   ...
│
└───app2
    └───templates
        ├───base.html (extends from core/base.html, only touches app2)
        └───file2.html (extends from app2/base.html)
    ...

To connect app1's template to core's I use {% extends '../../core/templates/base.html' %}, in the core app there'll be {% block container %}{% endblock %} as example and in app1, app2 there'll be other {% block other_content %}{% endblock %} blocks. as you can see blocks are nested too.

The issue is that I get this error :

The relative path ''../../core/templates/base.html'' points outside the file hierarchy that template 'base.html' is in.

Question: I was wondering what was the best approach to resolve this issue without hardcoding it?

1 个答案:

答案 0 :(得分:0)

The original base.html had conflicts with others of his kind, so I renamed app1, app2's base to base[app_name].html which resolved my issue. The tree would look like this :

├───core
│   └───templates
│       └───base.html (original, touches every page)
│   ...   
│
├───app1
│   └───templates
│       ├───base_app1.html (extends from core/base.html, only touches app1)
│       └───file1.html (extends from app1/base_app1.html)
│   ...
│
└───app2
    └───templates
        ├───base_app2.html (extends from core/base.html, only touches app2)
        └───file2.html (extends from app2/base_app2.html)
    ...

No need to hardcode the path either : {% extends 'base.html' %} is enough and {% extends 'base[app_name].html' %} for files withing the app's template.