Integrating and rendering 2 child templates into a

2019-08-07 04:53发布

enter image description here

I have a base template (index.html) and 2 child templates ipsum and need. I'm using blocks to try to integrate the 2 children into the base.

base.html

<html>
  <body>
  {% block 'body1' %}
    <p>testing 1</p>
  {% endblock %}
  {% block 'body2' %}
    <p>testing 2</p>
  {% endblock %}
  </body>
</html>

child1.html

{% extends 'base.html' %}
{% block 'body1' %}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
{% endblock %}

child2.html

{% extends 'base.html' %}
{% block 'body2' %}
<p>Quo usque tandem abutere, Catilina, patientia nostra?</p>
{% endblock %}

If there was only 1 block, I now understand that I could call in my view:

def index(request):
    return render_to_response('ipsum.html',context_instance=RequestContext(request))

What could I do to fill both blocks in index.html - 1 with ipsum.html and the other with need.html?

2条回答
够拽才男人
2楼-- · 2019-08-07 05:21

One way to achieve this would be to only have one block in the base template, and override that block in each child template, like:

base.html:

<html>
  <body>

      {% block 'content' %} gets overridden {% endblock %}

  </body>
</html>

child1.html:

{% extends 'base.html' %}

{% block 'content' %}

    <h1> Page 1 </h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>

{% endblock %}

child2.html:

{% extends 'base.html' %}

{% block 'content' %}

    <h1> Page 2 </h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>

{% endblock %}
查看更多
姐就是有狂的资本
3楼-- · 2019-08-07 05:34

You should ask the first child to extend the 2nd child which will extend base html. This is how you extend multiple child templates in django.

Hence your code should look like this:

index.html

<html>
<body>
  {% block 'body1' %}
  {% endblock %}
  {% block 'body2' %}
  {% endblock %}
</body>
</html>

ipsum.html

{% extends 'index.html' %}
{% block 'body1' %}
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
{% endblock %}

need.html

{% extends 'ipsum.html' %}
{% block 'body2' %}
    <p>Quo usque tandem abutere, Catsdsilina, patientia nostra?</p>
{% endblock %}

views.py

def index(request):
    return render_to_response('need.html',context_instance=RequestContext(request))

so need need.html will first be rendered, it will look for ipsum.html and when ipsum.html is rendered, it will look for index.html

Alternatively

If you will like to do inclusion instead of extension, I recommend using the Django Sekizai library http://django-sekizai.readthedocs.org/en/latest/ . It includes custom tags such as {% include 'xx.html' %} that will render the 2nd child template in your first child if needed.

Cheers, BioBirdMan

Here is a working example:

http://biobirdman.com/stacktest/nestedtemplate/

查看更多
登录 后发表回答