我试图找出如何调用我的基本html文件中的一个模型,它扩展到我的其他模板html文件中,以便在我的base.html文件中的导航栏中实现对购物车项目的查看。 通常情况下,我会使用上下文数据来调用视图中的模型(我使用的是基于类的视图),但这在base.html文件中是不可能的
这是如果它是一个带有视图的模板时将使用的代码
{% for item in orderitems %}
<div class="ps-product__thumbnail">
<a href="#">
<img src="img/products/clothing/7.jpg" alt="">
</a>
</div>
<div class="ps-product__content">
<a class="ps-product__remove" href="#">
<i class="icon-cross"></i>
</a>
<a href="product-default.html">MVMTH Classical Leather Watch InBlack</a>
<p><strong>Sold by:</strong> YOUNG SHOP</p><small>1 x $59.99</small>
</div>
{% endfor %}
(抱歉花了这么久才把事情弄清楚)
由于您仍然需要传入上下文数据,我将建议使用扩展技术。 例如:
# views.py
# doesn't have to be same, they're just examples
class OrderBaseView(ListView):
template_name = "order_base.html"
# add models, authentication, whatever
def get_context_data(self, **kwargs):
# handle the context data
return context
# this class extends the view above, and therefore
# will extend the get_context_data method.
class NextLevelView(OrderBaseView):
template_name = "next_level.html"
# your other handles here
# you can re-inherit the get_context_data call!
class AnotherView(OrderBaseView):
# more custom handles here
<!-- order_base.html -->
<!-- the code that you provided above -->
<!-- next_level.html -->
<!-- you can do whatever you want here first -->
{% include "order_base.html" %}
请重新检查include模板语法。
因此,您将在base.HTML
中拥有上下文数据(只是名称不同,因为它不是一个通用的基本HTML),但是您可以在多个地方重用它,如果您正确地处理它,上下文将会进入其中。
奖金
假设您的代码变得更加复杂,需要处理更多的上下文。 下面是你应该做的:
# views.py
class OrderBaseView(ListView):
# ...
def get_context_data_basic(self, **kwargs):
# handle basic context
return context
class NextLevelView(OrderBaseView):
# ...
# this method MUST be in this name because
# Django will look for it automatically. The
# basic handles are given a different name
# to prevent ambiguities.
def get_context_data(self, **kwargs):
# calls parent context data view
# remember to transfer the data to the main context
# be careful of name overlaps
temp = get_context_data_basic(self, **kwargs)
context = temp.copy()
# your other handles here
# ...
return context