您可以將可重複使用的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 %}
如果我們使用include和with tags,在這兩種情況下,我們都必須從主模板的視圖函數將對象傳遞給迷你模板。所以它又緊密耦合了嗎? 是否有任何其他方式,我可以從主模板帶有參數調用迷你模板,以便內部它將轉到該特定的視圖函數並返回響應? 但你的解決方案也是可以接受的,因爲現在我只做這樣一種方式。 –
您應始終在視圖函數中設置對象本身,但您可以在模板中以不同方式使用它們。而且該視圖甚至不一定需要了解迷你模板。 –
其他一些想法出現在我身上。 1)爲您的主視圖設置'精選圖書'混合,或2)使用JavaScript加載精選圖書子模板,並在獨立請求中加載視圖函數。這是不太可能的(據我所知)使用兩個視圖函數來處理請求 – mklauber