Django template interaction
Addresses
In an app,
From the templates/ directory in the project directory,
Extends
A template can contain blocks. These are initially declared empty,
You could add a comment,
How do I fill these blocks? Extend, similar to overriding methods from a base class,
This,
What happens if I put lines outside the blocks?
They are lost.
Can I stack templates?
Yes.
Can I choose to fill blocks later? In ’sitepage.html’,
Yes.
What if I fill the same block at different points in the stack? Let’s say the block ‘extra_css’ has entries in ‘page.html’ and ‘sitepage.html’. Output,
Latest entry wins, others are lost (similar to multiple overrides in class inheritance).
What happens if I introduce a new block in a subclass? Let’s say ‘page.html’ has a new block,
No. The analogy to class inheritance has broken down. Think about it and you will see that ordering is important to templates, unlike with classes. Django wouldn’t know where to place this new block. You would need to revise ‘base.html’,
Makes sense (how would you do that?). But also a limitation, because you need more blocks in the base, to account for possible overriding. And they cant be specific to the subclass.
Can I nest blocks? Can I introduce new blocks like that (on face, this seems to answer the question ‘Where does the template system place this new material?’)?
Yes. It feels tricky, but it works.
Includes
A snippet of template to use in another template.
Can you do this inside extend templates like the stack above? Yes. The ‘include’ must be inside a block.