将2个子模板集成并呈现到基础模板中 - Django [英] Integrating and rendering 2 child templates into a base template - Django

查看:141
本文介绍了将2个子模板集成并呈现到基础模板中 - Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有基础模板(index.html)和2个子模板ipsum和需要。我正在使用块来尝试将2个孩子整合到基础中。

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 p>

child2.html

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

如果只有1个块,我现在明白我可以调用我的观点:

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))

我可以做什么来填充index.html - 1中的两个块, ipsum.html,另一个是need.html?

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

推荐答案

你应该问第一个孩子延长第二个孩子,基础html。这是你如何在django中扩展多个子模板。

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:

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



ipsum.html



ipsum.html

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



need.html



need.html

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



views.py



views.py

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

所以需要 need.html 将首先被渲染,它将寻找 ipsum.html ,而当 ipsum.html 被呈现时,它将寻找 index.html

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

如果你想做包容而不是扩展,我建议使用Django Sekizai图书馆 http://django-sekizai.readthedocs.org/en/latest/。它包括自定义标签,例如 {%include'xx.html'%} ,如果需要,它将在第一个孩子中呈现第二个子模板。

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

Cheers, BioBirdMan

这是一个工作示例:

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

这篇关于将2个子模板集成并呈现到基础模板中 - Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆