slice Filter

Data Structure Most Useful

Argument: slice (required) – the slice to return.

Documentation

Returns a slice of a sequence.

Variable

company = 'Webucator'

Template

{{ company|slice:'4:7' }}

Result

cat

Commentary

This is extremely useful for querysets. For example, if you only want to show the first three results of your queryset and hide the rest under a “Show More” link, you use two loops with slicing:

<ol>
  {% for color in widget.colors|slice:':3' %}
    <li>{{ color }}</li>
  {% endfor %}

  {% for color in widget.colors|slice:'3:' %}
    <li class="collapse class-event-collapse">{{ color }}</li>
  {% endfor %}
</ol>
<button data-toggle="collapse" data-target=".class-event-collapse" class="class-event-dates">See More Colors</button>

Did we get something wrong? Is there a use case for the slice filter that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on Sept. 16, 2020, 7:34 p.m. EST