如何在 Django 模板中使用嵌套的 if else?

How to work with nested if else in django templates?

在这里,在这个项目中,我正在构建一个电子商务网站,并且我正在使用 Django。所以,在这里我想表明,如果没有类别 Electric 的产品,“抱歉,现在没有可用的产品!!!”将被显示。其中 n 是从应用视图发送到此模板的产品数量。 但是我没有收到 “抱歉,现在没有可用的产品!!!”,因为我的数据库中没有 Electric 类别的产品。如何解决这个问题?我哪里做错了?

views.py

def electric(request):

    product = Product.objects.all()
    n = len(product)
    params = {'product': product, 'range':range(1,n), 'n':n}
    return render(request,'electric.html',params)

electric.html

{% if n is 0 %}

    <div class="p-3 mb-1 bg-warning text-white text-center my-0">
        <h1><b>Sorry, No Product is Available Right Now !!! </b></h1>
    </div>
    
{% else %}

    <div class="album py-2 bg-gradient">
        <div class="container">
            <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">


                    {% for i in product %}
                        {% if i.category == "Electric" %}
                            <div class="col">
                                <div class="card shadow-sm">
                                    <img src="{{i.image}}" />
                                    <div class="card-body">
                                        <h4 class="card-title">{{ i.product_name}}</h4>
                                        <h6 class="card-subtitle mb-2 text-muted">
                                            Category: {{i.category}}
                                        </h6>
                                        <p class="card-text">{{i.description}}</p>
                                        <div class="buy d-flex justify-content-between align-items-center">
                                            <div class="price text-success">
                                                <h5 class="mt-4">Price: {{i.price}} BDT</h5>
                                            </div>
                                            <a href="#" class="btn btn-danger mt-3"><i class="fas fa-shopping-cart"></i> Add to Cart</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        {% endif %}      
                    {% endfor %}

                    
            </div>
        </div>
    </div> 

{% endif %}

views.py

def electric(request):
  product = Product.objects.all()
  return render(request,'electric.html',{'product': product})

electric.html

{% if  product.count > 0 %}
    
    --  your code  --      

{% else %}
    <div class="p-3 mb-1 bg-warning text-white text-center my-0">
      <h1><b>Sorry, No Product is Available Right Now !!! </b></h1>
    </div>
{% endif %}

Update your code as above. It will work.