【问题标题】:Django Jinja output first element of list and then start for loop from secondDjango Jinja 输出列表的第一个元素,然后从第二个开始循环
【发布时间】:2020-12-29 18:44:42
【问题描述】:

我是 Django 新手,我试图在第一个 div 中输出模型的第一张图片,在第二个 div 中输出所有其他图片。 我用谷歌搜索并没有找到任何解决方案。我敢肯定我的解决方案有点糟糕。

<div class="carousel-item active">
    <img src="{{ carousels[0].image.url }}" class="d-block w-100" alt="...">
</div>

{% for carousel in carousels([1]) %}
<div class="carousel-item">
    <img src="{{ carousel.image.url }}" class="d-block w-100" alt="...">
</div>
{% endfor %}

查看:

def product_list(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    products = Product.objects.filter(available=True)
    carousels = Carousel.objects.all()
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.filter(category=category)
    return render(request,
                  'shop/product/list.html',
                  {'category': category,
                   'categories': categories,
                   'products': products,
                   'carousels': carousels})

【问题讨论】:

  • 你确定你在使用 jinja 和 django 吗?
  • 我敢肯定,那个代码示例行不通,这就是我想象的样子

标签: python html css django jinja2


【解决方案1】:

如果您使用 Jinja,那么您可以使用常规切片([1:] 表示“从第二项开始的所有内容”):

<div class="carousel-item active">
    <img src="{{ carousels[0].image.url }}" class="d-block w-100" alt="...">
</div>

{% for carousel in carousels[1:] %}
<div class="carousel-item">
    <img src="{{ carousel.image.url }}" class="d-block w-100" alt="...">
</div>
{% endfor %}

vanilla Django 模板中的类似物是slice filter

{% for carousel in carousels|slice:"1:" %}

【讨论】:

    【解决方案2】:

    jinja的第一种方法应该没问题

    {% for carousel in carousels %}
    {% if forloop.counter == 0 %}
    <div class="carousel-item active">
        <img src="{{ carousel.image.url }}" class="d-block w-100" alt="...">
    </div>
    {% else %}
    <div class="carousel-item">
        <img src="{{ carousel.image.url }}" class="d-block w-100" alt="...">
    </div>
    {% endif %}
    {% endfor %}
    

    【讨论】:

    • 我很确定{% if forloop.counter == 0 %} 不起作用。应该是{{ loop.counter0 }} 不?
    • 但他们使用的是jinja2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    相关资源
    最近更新 更多