Eloque
Eloque

Reputation: 321

Nesting Django block with {% include %}

I am trying to nest blocks with Django 3. I have sections of html that are sometimes reused on a page. I don't think I would have to resort to duplicating templates, but I can't get it to work;

I have this template

{% extends 'base.html' %}
{% include 'site_part.html' %}

{% block content %}

Some Content

<br>
And here I insert the child content

{% block part_of_site %}
{% endblock %}

{% endblock %}

And the site_part_html is like this;

{% block part_of_site %}

Okay, i am loaded!

{% endblock %}

In the base.html I have only this:

{% block content %}
{% endblock %}

I'd expect it to render the "Okay, i am loaded!" string in the resulting page, in the content block. However, it remains empty. I've looked, but most examples are far more advanced then what I need and I can't get those to work either.

If I remove the extends statement at that start and the block content lines, it does load the included html.

Basically, I have a site part that sometimes is need, and I'd like to included that based on some templating. Otherwise, I'd have duplicate that code for each of the pages that it occurs on.

Upvotes: 1

Views: 1580

Answers (2)

Lomtrur
Lomtrur

Reputation: 1807

You need to move your {% include 'site_part.html' %} into the {% block content %} block.

content.html

{% extends 'base.html' %}

{% block content %}
Some Content

<br>
And here I insert the child content

{% include 'site_part.html' %}
{% block part_of_site %}
{% endblock %}

{% endblock %}

Then, in your view you need to return your content template. I named it content.html here.

def your_view(request):
    return render(request, "content.html")

You can put the include anywhere inside the content block, it doesn't have to be right before the part_of_site block.

Upvotes: 0

Andries D. Niemandt
Andries D. Niemandt

Reputation: 146

You may call the content from the block 'part_of_site' in any child template using {{ block.super }} like this:

{% extends 'site_part.html' %}

{% block content %}

  Some Content

  <br>

  {% block part_of_site %}
    {{ block.super }}
  {% endblock %}

{% endblock %}

You should use {% extends 'base.html' %} in the 'site_part.html' template. All children of 'site_part.html' will also be a descendant of base.html

{% extends 'base.html' %}  

{% block part_of_site %}
  Okay, i am loaded!
{% endblock %}

If you want to use {% include %} instead, change your code like this:

{% extends 'base.html' %}

{% block content %}

  Some Content

  <br>

  {% include 'site_part.html' %}

{% endblock %}

Upvotes: 1

Related Questions