Django共享模板

时间:2009-08-07 21:26:07

标签: django templates sharing

我正在寻找如何在Django中像ASP.NET中的UserControl那样做最好的事情。

例如: 1)定义了Book模型 2)我想在我的网站上使用这本书的常规表示(称为“book_template.html”)。

现在假设我想从2个视图中使用这个表示:recent_books_view,popular_books_view。它可以像

一样直接完成


from django import template

t = template.Template('My name is {{ name }}.') book1_context = template.Context({'book': Book1}) book2_context = template.Context({'book': Book2}) book3_context = template.Context({'book': Book3}) ...

render_to_response('recent_books.html', {'content': t.render(book1_context) + t.render(book2_context) + t.render(book3_context)})

render_to_response('popular_books.html', {'content': t.render(book4_context) + t.render(book5_context) + t.render(book6_context)})

但我确信有更好的方法......

例如,在ASP.NET中,您可以在模板文件“申请数组'书籍'这个共享模板”中说,然后在后端您只需指定变量'Books'。 Django有可能吗?

2 个答案:

答案 0 :(得分:3)

在你的python代码中:

context['books'] = blah blah # Make a list of books somehow.
return render_to_response('popular_books.html', context)

在popular_books.html中:

<p>Look, books:</p>
{% for book in books %}
    {% include "book.html" %}
{% endfor %}

最后,在book.html中:

<p>I am a book, my name is {{book.name}}</p>

有更多有趣的模块化方法,例如创建自定义标记,以便您可以,例如:

<p>Look, books:</p>
{% for b in books %}
    {% book b %}
{% endfor %}

答案 1 :(得分:0)

我认为你正在寻找这个教程Chapter 4 of the Django book: The Django Template System

请参阅块标记和模板继承。

相关问题