您可以将可重用的 HTML 块隔离到模板中,然后使用{% include %}
标记将它们包含在其他模板中。
它们不带参数,但您可以设置主模板以便正确设置变量,或者使用{% with %}
标签在{% include %}
作为一个具体的例子,您的视图代码可以设置这样的书籍列表:
def book_detail_view(request, book_id):
# Get the main book to display
book = Book.objects.get(id=book_id)
# Get some other books
featured_books = Book.objects.filter(featured=True).exclude(id=book_id)
just_in_books = Book.objects.filter(release_data__gte=last_week, featured=False).exclude(id=book_id)
return render("book_template.html",
dict(book=book,
featured_books=featured_books,
just_in_books=just_in_books))
然后,在您的模板(book_template.html)中:
<h1>Here's your book</h1>
<!-- fragment uses a context variable called "book" -->
{% include "book_fragment.html" %}
<h2>Here are some other featured books:</h2>
{% for featured_book in featured_books %}
<!--Temporarily define book to be the featured book in the loop -->
{% with featured_book as book %}
{% include "book_fragment.html" %}
{% endwith %}
{% endfor %}
<h2>Here are some other books we just received:</h2>
<!-- This is a different way to do it, but might overwrite
the original book variable -->
{% for book in just_in_books %}
{% include "book_fragment.html" %}
{% endfor %}