Jasper
Jasper

Reputation: 2231

Django overwrite parts in inherited templates

I have set up the following templates

base.html

{% extends 'base/main_base.html' %}

{% block main-content %}
    <h1>Header stuff<h1>
    ...
    {% block article-content %}
    {% endblock %}

{% endblock %}

article.html

{% extends 'base.html' %}
{% block article-content %}
   <h2>Content</h2>
   <p>More content</p>
{% endblock %}

Now, I connected a view to the article.html, and I want use the dynamic view data to overwrite the 'header stuff' in the 'base.html' template. Problem is, the view is connected to the article.html, which inherits from the base.

Is there a way to override parts of the base template from the child template?

Upvotes: 0

Views: 1023

Answers (2)

Jose Luis Barrera
Jose Luis Barrera

Reputation: 361

You could also check, in base.html, if a "header" value is injected to the template from the article (or any other view):

base.html

{% extends 'base/main_base.html' %}

{% block main-content %}
    <h1>
        {% if header %}
            {{ header }}
        {% else %}
            Header stuff
        {% endif %}
    <h1>
    ...
    {% block article-content %}
    {% endblock %}

{% endblock %}

Upvotes: 1

blacklwhite
blacklwhite

Reputation: 1958

You could create another template block in your base.html

{% extends 'base/main_base.html' %}

{% block main-content %}
    <h1>{% block header %}Header stuff{% endblock %}<h1>
    ...
    {% block article-content %}
    {% endblock %}

{% endblock %}

and overwrite the block in your article.html

{% extends 'base.html' %}

{% block header %}My overwritten headline{% endblock %}

{% block article-content %}
   <h2>Content</h2>
   <p>More content</p>
   ...
{% endblock %}

Upvotes: 2

Related Questions