你如何限制列表对象模板端,而不是视图端 [英] How do you limit list objects template side, rather than view side

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

问题描述

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

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天全站免登陆