Django Templates: Block and If statements don’t work like you might expect

I ran across this wrinkle in Django Templates at work the other day, and thought I should document what I found.

In a base template file, I had declared a block for use in page templates:

<!-- base.html -->

When I went to use that block in a page template, I wrapped that usage in an if statement based on a feature flag (which is a boolean value I had set in a settings file):

<!-- page.html -->
{% extends "base.html" %}

{% block feature %}
  <p>Stuff went here</p>
{% endblock %}
{% endif %}

Here's the thing - even with the feature flag set to False - the block on the page still rendered.

<!-- rendered page.html with FEATURE_FLAG = False -->
<p>Stuff went here</p>

It seems that the block declaration ignores/overrides the outer if statement. I don't know about you, but that was not what I expected.

The fix was to apply the feature flag boolean to the base template:

<!-- base.html -->

I was lucky that the blanket logic worked in this case, but it could have been an issue if I wanted more granular control.