我正在寻找 django 中的以下功能
我正在写一个网站,它包含很多页面,例如:首页(显示所有书籍),详细信息(所选书籍详细信息),搜索(根据搜索显示书籍)。
现在主页包含特色书籍、刚入库书籍、最著名的书籍等 block 。 详细信息页面显示所选书籍的详细信息,并且应该显示特色书籍、最著名的书籍。
现在我的问题被推荐了,著名的书籍 block 正在重复,所以有什么办法可以单独保留模板代码(html)以及单独的 View 方法。因此,如果我使用参数从主模板调用这些迷你模板。
这样我就可以保持更通用的方式,并且将来如果我想更改某些内容,我可以在一个地方完成,而无需重复代码。
我正在考虑用过滤器来做到这一点,但这是一个好方法吗?或者django提供了什么机制?
最佳答案
您可以将可重用的 HTML block 隔离到模板中,然后使用 {% include %}
将它们包含在其他模板中。标签。
它们不接受参数,但您可以设置主模板以便正确设置变量,或者使用 {% with %}
标记在 {% include %}
作为一个具体示例,您的 View 代码可以设置如下书籍列表:
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 %}
关于django - django中是否有任何tile类型的概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12480471/