【问题标题】:accessing a list of tuples in html访问 html 中的元组列表
【发布时间】:2015-02-04 02:50:36
【问题描述】:

我有一个名为 top_5 的元组列表,它们是前 5 个用户的用户名及其相应的帖子数。

这是一个包含 5 个项目的列表,每个项目有 2 个索引。

{% for user in top_5 %}
   {{ user }}
{% endfor %}

返回用户和他的帖子计数,但有没有办法可以单独获取它们?

【问题讨论】:

  • 这看起来不像 html 或 python?

标签: python html django django-templates


【解决方案1】:

这是一个 Django 模板吗?您可以使用点符号访问 Django 模板中的索引值:

{% for user in top_5 %}
    {{ user.0 }} {{ user.1 }}
{% endfor %}

如 cmets 所述,解包元组也是一种选择:

{% for username, post_count in top_5 %}
    {{ username }} {{ post_count }}
{% endfor %}

【讨论】:

  • 天哪。一个简单的点。我正在使用用户 [0]。非常感谢。
  • 或者你可以解压它们:{% for username, post_count in top_5 %}.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多