ZajcTeGleda
ZajcTeGleda

Reputation: 89

Django template remove trailing comma from for loop if contition is met

I'm creating a list of items with their attributes in Django. I'm getting items and their attributes from legacy database using sql stored procedures so option to get somthing like elegeant as {% for attribute in item.atributes_set.all %} is not posible.

What I have is this:

{% for article in articles%}
  {{article.title}}:
  {% for attribute in attributes %}
    {% if article.supplierID == attribute.SupplierID and article.ItemID = attribute.ItemID %}
      {{attribute.value}},
    {% endif %}
  {% endfor %}
{% endfor %}

Is there a was to remove trailing comma on the last item that meet if statement condition?

Upvotes: 2

Views: 1720

Answers (2)

Sergey Miletskiy
Sergey Miletskiy

Reputation: 487

It works for me:

{% for article in articles%}
  {{article.title}}:
  {% for attribute in attributes %}
    {% if article.supplierID == attribute.SupplierID and article.ItemID = attribute.ItemID %}

      {% if not forloop.last %}
         {{ attribute.value }},
      {% else %}
         {{ attribute.value }}
      {% endfor %}

    {% endif %}
  {% endfor %}
{% endfor %}

forloop.last

https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#for

Upvotes: 4

Satevg
Satevg

Reputation: 1601

I don't like such logic in template, so I can suggest to move it into view. Update context passed into template in following way:

articles_data = dict()
for article in articles:
    # following line is little bit long, but you can rewrite it with regular for loop
    # Note, attribute values should be in list
    articles_data[article.title] = [attribute.value for attribute in attributes \
                            if article.supplierID == attribute.SupplierID and article.ItemID = attribute.ItemID]

When you'll pass articles_data into template you can simply do:

{% for title, attributes in articles_data.items %}
    {{title}}:
    {{attributes|join:', '}}
{% endfor %}

Upvotes: 1

Related Questions