问题
I have my index.html file in /templates
directory and I have another index.html located in /templates/hello
.
I've created a file named templates.html in /templates/hello
and it should extend index.html.
Can I make template.html extends both index.html files (from both directories) using {% extends index.html %}
tag in it?
Thanks.
回答1:
You cannot extend from multiple django templates.. it's a single line inheritance.
If you want /templates/index.html
to be your base index template, and /templates/hello/index.html
to be your index template for the hello part of your application.. then you should have /templates/hello/index.html
start with {% extends 'index.html' %}
.
The thing to understand with Django templates is that the base template.. the one that is 'extended', is THE template.. and everything in that template will be displayed whether it is within a block tag or outside one.
When you 'extend' a template, any blocks declared which match blocks in the template that was extended, will override the content of those blocks.
Most web sites/applications have a more or less consistent layout from page to page. So, a typical template setup would be to have a master template that contains blocks for all the various parts of the page, with divs and css to arrange the layout the way you want. Put as much as the common html.. the stuff that does not change often from one page to the next, in that base template, and make sure the base template contains blocks for anything you need to fill in when you extend the template. These blocks can contain default html which will be shown if the extending template does not override that block. Or they can be empty.
Then, for each new template variation that you need, extend the master template and override only those blocks that need to be filled in or overrriden.
Don't think of the extend as bringing the code of your base template into the template that is extending it.. Django templates do not work like that. Think of the base template as THE template which has all the basic building blocks of your page, and then the extension MODIFIES the blocks of the template that it extends.
If you have a different situation where the pieces of your page need to be defined in different templates and you wish to piece them together, then what you are looking for is the {% include 'templatename' %}
tag.
来源:https://stackoverflow.com/questions/32513828/how-does-djangos-extends-work