Reputation: 4129
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?
Upvotes: 2
Views: 8400
Reputation: 18972
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 %}
Upvotes: 2