【问题标题】:Get element of list by variable in Django template在Django模板中通过变量获取列表元素
【发布时间】:2019-09-27 11:58:44
【问题描述】:

我在 Django 模板中有一行代码:

<h4>{{ totals.date.weekday }}</h4>

Totals 是 Python 列表,我如何通过存储在 date.weekday 中的索引获取此列表的项目?

这在 Python 中看起来像这样:

totals[date.weekday]

创建另一个存储 date.weekday 的变量不起作用

UPD:

我找到了解决办法:

刚刚将totals 列表的元素添加到渲染中的模板上下文

例如:

# ... 
return render(request, 'template.html', context={'date_total'=totals[date.weekday()]})

【问题讨论】:

  • 这里你试图访问这个:totals[date[weekday]],对吧?
  • @Plopp,我正在尝试访问totals[date.weekday]
  • @Greenfield 能否请您发布您想要迭代的示例列表。
  • @lok​​esh python totals = [ time(0, 0), time(0, 0), time(0, 0) ] 我想使用date.weekday 作为 Django 模板中totals 列表的索引
  • date.weekday 不能是变量名。在 django 中,点是快捷方式,date.weekday 表示date[weekday]。尝试设置和使用date_weekday。

标签: python django


【解决方案1】:

您可以使用直接访问数组

{{ totals.0.date.weekday}} 其中 0 是您想要的位置。

此外,如果您想打印所有元素,则需要一个 for 循环,例如:

{% for d in totals %}
   {{ d }}
{% endfor %}

关于排序,你可以使用管道 order_by 但我建议你传递已经从视图中排序的列表

【讨论】:

  • 这不是我想要的,我想获取列表元素的位置,存储在date.weekday变量中
【解决方案2】:

你必须为此运行“for循环”。

{% with counts = 0 %}
{% while counts < totals.count %}
      {% if counts == date.weekday %}
           <h4>total.counts</h4>
      {% endif %}
      {% counts += 1 %}
{% endfor %}

我没有完全理解你的问题,但我认为这可能会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-01-29
    • 1970-01-01
    • 2016-07-10
    • 2018-08-06
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多