Search code examples
pythondjangodjango-templatesdjango-template-filters

FOR OR statement in django template


I want to minimize my code in my template because the items i would like to display are many. The variables to output are the same and im using the same template. The details are below

i tried for or statement but the error i get is 'for' statements should use the format 'for x in y': for item in (shoe_list or cup_list)

This is the original code

{% extends 'base_generic.html' %}
{% load static %}
{% block content %}


<body>

  <h1 class="titleheadline"> List of items</h1>

{% if shoe_list %}
    {% for item in shoe_list %} 
      <td>{{req.colour}}</td>
      <td>{{req.size}}</td>
      <td>{{req.price}}</td>
  {% endfor %}

{% elif cup_list %}
    {% for item in cup_list %}

      <td>{{req.colour}}</td>
      <td>{{req.size}}</td>
      <td>{{req.price}}</td>

  {% endfor %}

  {% else %}
    <p>There are none in stock.</p>
  {% endif %}

</body>      

{% endblock %}

The below are the changes i made which is not working

{% extends 'base_generic.html' %}
{% load static %}
{% block content %}

<body>

  <h1 class="titleheadline"> List of items</h1>

{% if shoe_list or cup_list  %}
    {% for item in (shoe_list or cup_list) %} 
      <td>{{req.colour}}</td>
      <td>{{req.size}}</td>
      <td>{{req.price}}</td>
  {% endfor %}
  {% else %}
    <p>There are none in stock.</p>
  {% endif %}

</body>      

{% endblock %}

I expect to reduce the code to give the same result like the original code.


Solution

  • One approach is to combine these lists on the server side and then loop over the one single list which contains everything in the template.

    For example:

    views

    # If shoe_list and cup_list are querysets
    from itertools import chain
    combined_list = list(chain(shoe_list, cup_list))
    

    template

    {% for item in combined_list %} 
        <td>{{item.colour}}</td>
        <td>{{item.size}}</td> 
        <td>{{item.price}}</td>
    {% else %}
        There are none in stock.
    {% endfor %}