【问题标题】:FOR OR statement in django templatedjango 模板中的 FOR OR 语句
【发布时间】:2019-10-21 07:43:23
【问题描述】:

我想在我的模板中最小化我的代码,因为我想显示的项目很多。要输出的变量是相同的,并且我使用相同的模板。详情如下

我尝试了 for or 语句,但我得到的错误是“for”语句应该使用格式“for x in y”:for item in (shoe_list or cup_list)

这是原始代码

{% 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 %}

以下是我所做的无效更改

{% 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 %}

我希望减少代码以提供与原始代码相同的结果。

【问题讨论】:

    标签: python django django-templates django-template-filters


    【解决方案1】:

    一种方法是在服务器端组合这些列表,然后循环遍历包含模板中所有内容的单个列表。

    例如:

    观看次数

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

    模板

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

    【讨论】:

      猜你喜欢
      • 2021-06-30
      • 1970-01-01
      • 2013-10-17
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 2011-06-01
      • 1970-01-01
      相关资源
      最近更新 更多