views:

205

answers:

3

My friend and I are having a small argument. In my current Django Project, I have created a file called menu.html which will contain a bunch of links configured and formatted into a list. Instead of manually hard-coding the menu into each page, I am currently including the menu using the following Django/Python code:

{% include 'menu.html' %}

However, my friend is suggesting that this is the incorrect way to do it. He said I need to use extends instead of include and then define content, something like this:

{% extend 'menu.html' %}
{% block content %}
The rest of my content here.
{% endblock %}

That's a bit of extra code. Does it really matter which I use? I would prefer to use the former.

+1  A: 

Yes, it matters. First of all extends can only occur as the very first line of the file. Secondly, include pushes and pops a context object on the resolve stack, which means that value created in the context while in the include will go out of scope when it returns.

My rule is: create base.html template files that define the overall structure of your site and use liberal amounts of {% block foo %} around critical areas. Then all of your other templates extends the base (or something that itself extends the base) and you replace those blocks as needed.

include, on the other hand, is good for encapsulating things you may need to use in more than one place, maybe even on the same page.

Peter Rowell
A: 

( his friend )

What I actually meant was defining a base.html so you can inherit a base template consistent of several generic sections, this one includes the doctype, html element defines 3 blocks for content and nav and optional area to override/insert script/link elements in the head.

<!doctype>
<html>
<head>
{%block extrahead %} {%endblock %}
</head>
{%block nav %}
<nav>
  <ul>
    <li>home</li>
  </ul>
</nav>
<div id="content">
{% endblock %}
{%block content %}
{% endblock %}
</div>
</html>

Then you can define homepage.html:

{% extends "base.html" %}

{% block content %}
homepage content
{% endblock %}

homepage.html would then have the navigation because it extends base.html.

meder
A: 

In this case placing the menu in base.html and extending from this seems to be more senseful.

including is great for splitting complex template and reusing those chunks.

let's say, you use the same list-style in different places of the site, but you send other queryset to it. as long, as you call the querysets the same, you only need to write the template code once.

Here I use differnt templates for normal- and ajax-requests. But using include let me re-use most parts in both templates

vikingosegundo