Reputation: 403
This is my django template file:
{% if chart %}
{% block chart_content %}
// some for loop
{% endblock %}
{% else %}
{% block content %}
{% endblock %}
{% endif %}
And here's my "base.html":
<div class = "container">
{% block content %}
{% endblock %}
</div>
{% block chart_content %}
{% endblock %}
When the above template is rendered, both the "if" and "else" content appears in the page. So in other words, both "if" and "else" are evaluated. Can anyone show me what is the problem?
Upvotes: 2
Views: 5406
Reputation: 12164
The other answers are correct about the templating rules. However if you just want to fix your results, maybe something like this would do the trick.
{% block chart_content %}
{% if chart %}
// some for loop
{% endif %}
{% endblock %}
{% block content %}
any conditionals you see fit on
the contents of this block
for example:
{% if not chart %}
it did see like you wanted
to have something here
if chart was empty
{% else %}
{% endif %}
{% endblock %}
Upvotes: 2
Reputation: 6637
In "base.htm" template you determined and used blocks, by default you see these blocks content and on the inherited templates you can only override content of blocks that determined in parent template, you can not set appear or disappear blocks, you can disappear inherited blocks by re-determining blocks without content:
{# base.html #}
{% block x %}The X Block{% endblock %}
and in inherited:
{# index.html #}
{% extends "base.html" %}
{% block x %}{% endblock %}
Upvotes: 0
Reputation: 318
From Django template if statement always evaluates to true:
You can't wrap control flow tags like if around a block. Your problem is that the child template's definition for block data is being used simply because it's there.
You can fix it by placing the if tag inside block data. If you want to inherit the parent's contents when the list is empty, add an else case that expands to {{ block.super }}.
Upvotes: 3