I have a template named base.html. As the name suggests, it is where the header and footer reside. In between these 2 elements, is a {% block content %} where the child template can extend this template and add content inside block content.
However, inside header I want the user's name to be shown. For example, {{ user.username }} but Django can't seem to recognize this when I extend this template to a child template. Is there a way I can pass in objects to the extends template? That way the logged in user's name is shown?
This is a rough example of what I'm trying to do. user.username does not show even when the user is logged in.
base.html
<header>
<h1>Hello, {{ user.username }}</h1>
</header>
{% block content %}{% endblock %}
<footer>
///Some content
</footer>
child.html
{% extends 'base.html' %}
{% block content %}
//Some content
{% endblock %}
views.py for child.html
ChildView(TemplateView):
template_name = 'child.html'
In your child template add this to the top
{% extends 'base.html' %}
This will allow you to "inherit" the context variable.
Alternatively, if you only want to pass say just the user data to the template, you could do the following in your base.html
{% include 'header.html' with my_user=user %}
This answer summarises the differences between extend and include functionality quite well.
Edit:
In response to your comments and updated question, you aren't accessing the user object correctly. To do so you must use {{ request.user }}. This is because there is a context processor that passes the user object to every template.
As an aside, if you were to explicitly send the user from the view, you could then access the user with {{ user }} as you have done. However, this is obviously quite unnecessary.
That is because the content in blocks in child templates are overriden.
base.html
{% block my_block %}
This content is overriden by child templates
{% endblock my_block %}
child.html
{% extends 'base.html' %}
{% block my_block %}
This content is shown
{% endblock my_block %}
If you want some content shown in all templates, you shouldn't put inside a block content, but directly in your base template.
base.html
{{ user.username }}
{% block my_block %}
This content is overriden by child templates
{% endblock my_block %}
So, it all comes down to how the layout of your page is done. If the header is always the same, you should not use the block tag.
If it's almost the same, but changes in details, use blocks to change the details:
header:
<h1>This doesn't change ever
{% block this_changes %}
the child themplate will provide the content
{% endblock this_changes %}</h1>
<b>User: {{ user.username }}</b>
Related
I am fairly new to django and am trying out template-inheritance but not able to get it work. I cannot get all the blocks in a page to be displayed simultaneously. Not sure if I am missing something in urls, views or settings. I am using Python 3.6 in venv / Django 2.0.4 on PyCharm
Details of my example below - myhome being project name and smarthome being app name
Folder Structure
base.html
navtopbar.html
navsidebar.html
smarthome urls.py
smarthome views.py
-- Initially I had this as base.html but based on advice in thread below, changed to navtopbar. But then not sure how to get application to display navsidebar simultaneously
settings
I followed the advice in this thread but not able to get it to work yet. Appreciate any help here.
First of all careful with naming!
You are rendering your view in navtopbar.html
In navtopbar.html you have only override navtopbar block so only that block will replaced.
Djnago template works as below:
base.html
{% block body %} base {% endblock %}
{% block content %} base {% endblock %}
Now if you render home.html from view it should be:
home.html
{% extends 'base.html' %}
<!-- the blocks you override here only replaced -->
{% block body %}
home
{% endblock %}
As above html you have only overridden one block which results to override one block and other remains unchanged. the if you want to override {% block content %} you need to override in same html as below:
home.html
{% extends 'base.html' %}
<!-- the blocks you override here only replaced -->
{% block body %}
home
{% endblock %}
{% block content %}
home content
{% endblock %}
If you want to include content from another html you can include it with include tag
consider below file:
content.html
<h3>This is common content</h3>
now you can include this in your home.html as below:
home.html
{% extends 'base.html' %}
<!-- the blocks you override here only replaced -->
{% block body %}
home
{% endblock %}
{% block content %}
{% include 'content.html' %}
{% endblock %}
I have a download page on a Django site that I want to serve for both users who are logged in and who aren't. Instead of having a user_download.html and login_download.html, I want to have a single download.html that conditionally extends the correct base.
However, I get an error when I use the following code.
{% if user.is_authenticated %}
{% extends 'user_base.html' %}
{% else %}
{% extends 'login_base.html' %}
{% endif %}
{% block content %}
<h2>Downloadable content</h2>
...
{% endblock %}
The error I receive is
TemplateSyntaxError at /download/
Invalid block tag: 'else'
What's wrong with the else? I tried
{% if user.is_authenticated %}
{% extends 'user_base.html' %}
{% else %}{% if AnonymousUser.is_authenticated %}
{% extends 'login_base.html' %}
{% endif %}{% endif %}
{% block content %}
<h2>Downloadable content</h2>
...
{% endblock %}
but this didn't work, either.
Thanks,
erip
The {% extends %} tag supports variables. See the doc for reference.
def my_view(request):
if request.user.is_authenicated
base_template_name = 'user_base.html'
else:
base_template_name = 'login_base.html'
# Pass base template name to the renderer
return render_to_response('your_template.html', {'base_template_name':base_template_name})
Template (please note that the value is not quoted):
{% extends base_template_name %}
...
You're getting an error because extends needs to be defined at the top of the template. extends controls template inheritance: you are basically creating a subclass from some parent class, which is why extends needs to be the first thing in the template.
Imagine writing a class, and in the __init__() you said something like
class DoesntKnowWhereToInheritFrom(object):
def __init__():
if something:
self.inherits_from(x)
else
self.inherits_from(y)
The compiler/interpreter would freak out.
The common way to do what you are trying to do here is to check for is_authenticated in the view, and then render the appropriate template.
If I have this in my "main" (or project's) base.html:
{% block content %}
I'm inside block content.
{% block main_sidebar %}
I'm inside my sidebar now.
{% endblock main_sidebar %}
{% endblock %}
And, in the app's base.html (this base extends off the main base.html), I have this:
{% block main_sidebar %}
I want to change this.
{% endblock main_sidebar %}
The output doesn't change in my app's base.html for the main sidebar.
If I change {% block content %} to a custom name, then it works. I guess {% block content %} has special privileges as a block name and so can't be overwritten in a case like the one above?
I need to create a small side block with form(it contains only one field and button) and I want it to be included to every page except base.html
I thought about making simple view function, but maybe there are better ways to do this?
I'm using Python and Django 1.6
In general, you shouldn't use base.html directly, but because you are and because it would be a huge hassle to change it in every other template, what you can do is, in the view function that returns base.html, you can add a boolean to the context and check the boolean to determine what template you are using.
Something like this:
def view_that_uses_base.html(request):
is_base = True
return render_to_response("base.html", {"is_base":is_base}, RequestContext(request,{}))
And then in the template:
{% block sidebar %}
{% if is_base%}
{% else %}
#Your code here
{% endif %}
{% endblock sidebar %}
You must use templates to do that.
In other words, try creating $DJANGO_ROOT/templates/main.html using the following code:
<html>
<head>
</head>
<body>
{% block one_field_and_a_button %}
<input />
<button>I am everywhere</button>
{% endblock %}
{% block my_custom_content %}
{% endblock %}
</body>
<html>
Then all other templates must extend that main.html template and insert their own data.
Imagine this is $DJANGO_ROOT/templates/login.html. It will only replace "my_custom_content" and will inherit all other blocks including "one_field_and_a_button"
{% extends 'templates/main.html' %}
{% block my_custom_content %}
Hello World! This is the login
{% endblock %}
Finally, if you want to have a base.html that does not have that part of the code containing one field and a button, you can do the following.
Imagine this is $DJANGO_ROOT/templates/base.html. It will replace both "one_field_and_a_button" and "my_custom_content". However, in this case, "one_field_and_a_button" will be replaced with blank space that will not show in your html code.
{% extends 'templates/main.html' %}
{% block one_field_and_a_button %} {% endblock %}
{% block my_custom_content %}
Hello World! This is my base.html template
{% endblock %}
Hope it works for you!
You can use block tag in base.html, i think you are searching foe something like this
base.html
{% block code %}
{% include 'sidebar.html' %}
{% endblock %}
index.html
{% extends base.html %}
{% block code %}
{% endblock %}
and every other templates
just extend base html
{% extends base.html %}
The main question is how can I programatically choose what block to put some content in. The following is working in a different project, but in a fresh project this does not work for some reason. I'm using the same (default) template context processors on the same machine for both projects.
I have a base template that goes something like this
...
{% block Title %}<h1>Whoo</h1>{% endblock %}
{% block Content %}<p>Hi there</p>{% endblock %}
...
And an extending template like this
{% extends "base.html" %}
...
{% block myblock.name %} <p> {{ myblock.content }} </p> {% endblock %}
<p> {{ myblock.name }} </br> {{ myblock.content }} </p>
...
And rendering as such
myblock = { 'name': 'Title', 'content': 'stuff' }
return render_to_response( 'extended.html', {'myblock': myblock}, context_instance=RequestContext(request) )
I expect to get, and get on the first project:
...
<p> stuff <p>
<p>Hi there</p>
<p> Title </br> stuff </p>
...
But on the second project I get
...
<h1>Whoo</h1>
<p>Hi there</p>
<p> Title </br> stuff </p>
...
So on the second project, the myblock dict is passed and processed by the template but it seems that the myblock.name in {% block myblock.name %} is interpreted as a literal and not a variable. Any ideas on how to force Django to evaluate a variable inside a {% block %} tag?
You should take another look at the documentation about template inheritance.
... the block tag defines [...] blocks that child templates can fill
in. All the block tag does is to tell the template engine that a child
template may override those portions of the template.
But you don't assign a variable to a block directly in a view as you are trying to do.
And {% block myblock.name %} looks strange too.
To receive the result you are expecting I'd say the template should rather look like this
{% extends "base.html" %}
{% block Title %}<p>{{ myblock.content }}</p>{% endblock %}
Assuming you are using a recent version of Django you could even simplify things using the render shortcut in your view:
return render(request, 'extended.html', {'name': 'Title', 'content': 'stuff'})
Which would lead to a template like this:
{% extends "base.html" %}
{% block Title %}<p>{{ content }}</p>{% endblock %}