如何限制列表对象模板一边,而不是查看一边 [英] How do you limit list objects template side, rather than view side

查看:128
本文介绍了如何限制列表对象模板一边,而不是查看一边的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限制对象的一种方法是为这样的函数添加限制

One of the ways to limit objects is to add a limitation to a function like this

def ten_objects():
    obj = Model.objects.all()[0:10]  # limit to 10
    return {'objects': obj}

然而,如何在模板中实现,而不是在视图中实现?

However how do you achieve this inside a template rather than inside a view?

我知道您可以过滤模板中的对象并限制字符,但是如何实际限制循环中显示的对象数量。通过模板例如,以下代码将循环遍历所有对象....

I know you can filter through objects within a template and limit characters but how do you actually limit the amount of objects displayed in a loop. Via the template. for example the following code will loop through all objects....

    <ul>
     {% for new in news %}
      <li>
       <p>{{ news.title }}</p>
       <p>{{ news.body }}</p>
      </li>
     {% endfor %}
    </ul>

如何在第3个对象/项目之后打破循环。我如何在模板中做到这一点。感谢提前。

How do I break the loop, say after the firs 3 objects/items. And how do I do it inside the template. Thanks in advance.

推荐答案

有一个 slice 过滤器,您可以在模板中使用。

There is a slice filter that you can use in templates. This works exactly the same as slicing within the view.

{% for new in news|slice:":10" %}

这篇关于如何限制列表对象模板一边,而不是查看一边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆