这是我的 main.html,我目前包括页眉和页脚
{% include "store/header.html" %}
{% block content %}
{% endblock content %}
{% include "store/footer.html" %}```
我的 header.html 示例:这是我试图呈现我的购物车的地方
<div class="shopping__cart">
<div class="shopping__cart__inner">
<div class="offsetmenu__close__btn">
<a href="#"><i class="zmdi zmdi-close"></i></a>
</div>
<div class="shp__cart__wrap">
{% for item in items %}
<div class="shp__single__product">
<div class="shp__pro__thumb">
<a href="#">
<img src="{{item.product.imageURL}}" alt="product images">
</a>
</div>
<div class="shp__pro__details">
<h2><a href="product-details.html">{{item.product.title}}</a></h2>
<span class="quantity">QTY: {{item.quantity}}</span>
<span class="shp__price">${{item.product.price|floatformat:2}}</span>
</div>
<div class="remove__btn">
<a href="#" title="Remove this item"><i class="zmdi zmdi-close"></i></a>
</div>
</div>
{% endfor %}
</div>
<ul class="shoping__total">
<li class="subtotal">Subtotal:</li>
<li class="total__price">${{order.get_cart_total|floatformat:2}}</li>
</ul>
<ul class="shopping__btn">
<li><a href="cart.html">View Cart</a></li>
<li class="shp__checkout"><a href="checkout.html">Checkout</a></li>
</ul>
</div>
</div>
我正在尝试将商品呈现到我的购物车中。
这是我的观点:
def header(request):
category = None
categories = Category.objects.all()
products = Product.objects.all()
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
data = cartData(request)
cartItems = data['cartItems']
order = data['order']
items = data['items']
context = {'items':items, 'order':order, 'cartItems':cartItems, 'categories':categories, 'products':products, 'category': category}
return render(request, 'store/header.html', context)
但我不知道如何渲染它,因为它只是一个标题。也许我应该以不同的方式看待它。
答案 0 :(得分:0)
您可以使用 Template tags。 Django 有模板标签来执行模板中的复杂操作。
您可以做的是创建一个自定义模板标签,它将用户作为输入并返回购物车商品的查询集,您可以将其保存在一个变量中,然后遍历它以显示所有商品。
>在 myprojectdir/app_name/templatetags/cart.py 中
from django import template
from myapp.models import Customer
register = template.Library()
@register.simple_tag
def get_cart_items(user):
//Implement the filter logic to get the cart items for the user and then return th queryset
cart = Cart.objects.filter(user=user)
return cart
然后在你的模板中你可以这样做
{% load cart %}
{% get_cart_items request.user as cart_items %}
{% for item in cart_items %}
<Your html code>
{% endfor %}
由于 Django 自动将上下文中的 request
传递给所有模板,因此您应该使用 request.user
访问当前用户。
要了解在何处创建模板标记文件,请参阅此 https://docs.djangoproject.com/en/3.1/howto/custom-template-tags/#code-layout
有关模板标签的更多信息,请参阅:
您也可以使用 Inclusion tag 而不是简单的标签以获得更大的灵活性和代码可重用性。