Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template: use of multiple block tags in same base

I want to make sure I have understood this correctly before I change all my templates. I have a base.html with my overall layout. This has a {% block content %}. Each of my content pages extends "base.html" and is surrounded by the block tag. This works great. My view returns the rendered content page and it's placed nicely in the layout.

Now I have also created a menu bar in menubar.html The menu should be the same for every page except that the color of the selected page/content is different. So it needs to know what content got loaded.

My base.html now also has a {% block menubar %}

I am about to open up all of my content templates and add the following to them:

{% include "menubar.html" %}

Then, in menubar.html, I will surround the menu with block tags. Is that correct? I thought the point of the block system was that somehow things could be controlled more from the base.html, without changing all my templates.

like image 776
user984003 Avatar asked Oct 15 '12 16:10

user984003


People also ask

What does {% endblock %} mean?

{% endblock %} </div> </body> </html> In this example, the {% block %} tags define four blocks that child templates can fill in. All the block tag does is tell the template engine that a child template may override those portions of the template.

What does {% %} mean in Django?

This tag can be used in two ways: {% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend. {% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template.

Why is {% extends %} tag used?

The extends tag is used to declare a parent template. It should be the very first tag used in a child template and a child template can only extend up to one parent template. To summarize, parent templates define blocks and child templates will override the contents of those blocks.

What does {% include %} do?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.


2 Answers

I'd suggest just putting {% include "menubar.html" %} into base.html.

To highlight the current page in your menu use something like this: https://stackoverflow.com/a/477719/473285

like image 108
scytale Avatar answered Sep 19 '22 19:09

scytale


If your content templates extends from base.html, and the {% block menubar %} is outside the {% block content %} you don't need to modify all the contents templates, just the base.html

like image 29
esauro Avatar answered Sep 20 '22 19:09

esauro