Django循环-删除最后一个逗号

ezykj2lf  于 2023-05-19  发布在  Go
关注(0)|答案(3)|浏览(92)

我设置了以下循环,但需要删除最后一项上的逗号(这是为了复制cycle2的JSON数组)

{% for product_in_series in series.get_products %}{%spaceless%}
    {% with product_in_series.product as product %}
    {%if not forloop.first%}
            "<img src='{% version product.get_overview 'page_image' %}'>",
    {%endif%}
    {% endwith %}
{%endspaceless%}{% endfor %}

干杯

qco9c6ql

qco9c6ql1#

那这个呢

{% for product_in_series in series.get_products %}{%spaceless%}
    {% with product_in_series.product as product %}
    {%if not forloop.first%}
        "<img src='{% version product.get_overview 'page_image' %}'>"
        {%if not forloop.last%},{%endif%}
    {%endif%}
    {% endwith %}
{%endspaceless%}{% endfor %}
qgelzfjb

qgelzfjb2#

{{ forloop.last|yesno:",&#44;"|safe }}

&#44;-是逗号

pbwdgjma

pbwdgjma3#

以上都不适合我。Django3.0中的正确语法是这样的

{% with querythisandthat as A %}
   {% for  u in A %}  {{ u.interesting_stuff }} 
      {% if u == A.last %} . {% else %} ; {% endif %}
   {% endfor %}
 {% endwith %}

原因是A.last不是True/False,但它是查询集的最后一个元素
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.first

相关问题