【问题标题】:Django - Limit the number of objects in Django templateDjango - 限制 Django 模板中的对象数量
【发布时间】:2017-10-22 17:00:44
【问题描述】:

我以前用 C# 编写代码。我想用 Python 做类似的事情:

int start_index = 4;
List<int> list = { ... }
for(int i = start_index;i < 10;i++){
     list[i].dosomething();
}

这就是我在 Django 中尝试的方式

{% with 0 as starting_index %}
{% for comment in comments %}
<!--set a variable to limit the amount of comment on a page-->
{% with forloop.counter as index %}
{% if index < 3 %}
<div class="comment_body">
    <div class="content_block">
        <p>{{comments[index]}}</p>
    </div>
</div>
{% endif %}
{% endwith %}
{% endfor %}
{% endwith %}

这段代码显然不起作用。有人可以帮我解决这个问题吗? 提前致谢!

【问题讨论】:

  • 我认为与其在模板中这样做,不如在视图中这样做。这有意义吗?
  • @RajKris 你是对的,我忘了我们可以使用视图,哈哈
  • 希望对您有所帮助!干杯。

标签: python django tags web


【解决方案1】:

如果你想在模板中这样做,你可以使用内置的 django 模板标签切片:

{% for new in comments |slice:":3" %}

在模板中切片为所需的对象数量。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2016-11-12
    • 2017-11-27
    • 1970-01-01
    • 2011-07-22
    • 2016-03-26
    • 2021-02-22
    • 2011-08-25
    • 2011-09-28
    相关资源
    最近更新 更多