How do you limit list objects template side, rather than view side

♀尐吖头ヾ 提交于 2019-12-17 17:33:57

问题


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>

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.


回答1:


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" %}



回答2:


You want to use the slice template filter

Here's your example altered to use it:

<ul>
{% for new in news|slice:":3" %}
<li>
<p>{{ new.title }}</p>
<p>{{ new.body }}</p>
</li>
{% endfor %}
</ul>


来源:https://stackoverflow.com/questions/3907628/how-do-you-limit-list-objects-template-side-rather-than-view-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!