django template extends not working
Asked Answered
A

5

15

This is my base.html

<!DOCTYPE html> 
<head> 
<title> My Site </title>
</head> 
<body>
<div id="wrapper">  
<!-- HEADER START -->
{% block nav %} {% endblock %}
{% block index %} {% endblock %}
</div> 
</body>
</html>

this is my nav.html

{% extends "base.html" %}
{% block nav %}
<div id="header"> 
<div class="inner">

<div class="nav"> 
<ul> 
<li class="current"><a href="index.html">Home</a></li> 
<li><a href="about.html">About</a></li> 
<li><a href="blog_right.html">Blog</a></li>                        
<li><a href="contact.html">Contact</a></li> 
</ul>                     
</div>  
<div class="clear"></div>           
</div><!-- .inner end --> 
</div><!-- #header end --> 
<!-- HEADER END -->
{% endblock %}

this is my index.html

{% extends "base.html" %}
{% block index %}
<p> hello </p>
{% endblock %}

I have done it several times before before but i am clueless as to why this is NOT working? the urls and views are here.

Area answered 31/12, 2011 at 14:12 Comment(1)
What's the problem? "It's not working" isn't very helpful.Ahmedahmedabad
R
19

Well everything is fine, the trouble that you are having is that you are confused, just naming a block in base does not calls it. Mark the difference between extends and include. You have counfused extends to include.

Once in your views if you call say index.html it will be rendered properly. The effect you want can be achieved by changing the base.html in your views to index.html.

Hope this helps. more can be read here: https://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance

Rapier answered 31/12, 2011 at 14:20 Comment(2)
thanks, it seriously helped. and yeah i will remember that ... silly me :(Area
Anno 2019 your answer still flies! To add to your very clear explanation: if you use {% block something %} {% endblock something %} on a page, you should not reference this page in the views.py. Instead you have to refer the page that has the code you want to show in that block.Cleavers
W
3

For more people who end up here (as myself), main thing to note is that when you use {% extends 'something.html' %}, you cannot use anything other than these template tags at the top-level.

You can obviously have html tags inside these tags (like block tags), but don't put ANYTHING outside the template tags.

Wenz answered 30/11, 2015 at 12:39 Comment(0)
B
0

Also helps if you change the path in extends, for example {% extends 'mysite/index.html' %}. And view function must render the file with extends, not the basic one.

Boss answered 10/6, 2021 at 18:40 Comment(0)
A
0

In views.py, you have to call the template that extends the other template, not the other way around. In your example you should call nav.html.

Abirritant answered 9/1, 2023 at 17:35 Comment(0)
T
0

try do this

{% extends 'appname/index.html' %}
Torn answered 16/1, 2023 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.