【问题标题】:Django template. Best way for integer iterationDjango 模板。整数迭代的最佳方法
【发布时间】:2021-02-25 23:56:08
【问题描述】:

我想在 html 中显示与锦标赛对象中的循环一样多的表格。

我需要在Tournament 模型的字段loop_count 中按值进行迭代(不需要列表中的数字本身)。我在网上没有找到方法,所以我自己想出了。 有了财产,这是最好的办法吗?

锦标赛模型:

class Tournament(models.Model):
    name = models.CharField("Title",max_length=50,unique=True)
    loop_count = models.PositiveSmallIntegerField("Count of loop")

    @property
    def loop_count_list(self):
        return range(self.loop_count)

HTML:

{% for loop in tournament.loop_count_list %}
<div class="home-champ"...>
{% endfor %>

如果我需要列表中的数字本身,我可以执行以下操作:(我知道 forloop.counter)

HTML:

{% for loop in tournament.loop_count_list %}
<b>Index: {{ loop }}</b>
<div class="home-champ"...>
{% endfor %>

【问题讨论】:

  • Html 是锦标赛的详细视图
  • 这能回答你的问题吗? Numeric for loop in Django templates
  • 不,这个答案与模型的字段无关
  • 我会看看是否有一种方法可以迭代该 div 中表示的任何内容,并使用您提到的 forloop 计数器(或 html 有序列表)作为索引数字。看看您将如何以现在的方式在 div 中显示您的详细信息会很有趣。

标签: python django django-models django-templates


【解决方案1】:

如果这对你有用,我会同意的。

您可以编写一个自定义标签来完成几乎相同的事情。

这里还有一个 hacky(但聪明)的方法:https://stackoverflow.com/a/14389078/4872140

关于“最佳”方式的问题很棘手且令人沮丧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 2013-01-14
    • 2020-10-05
    • 2011-06-16
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多