How to Emulate Liquid's Offset & Limit Filters in Twig

• ~200 words • 0.8 minute read

When I work on Shopify themes in Liquid I often rely on the offset and limit filters on for loops to achieve various goals. In lieu of an actual server-side environment to properly prep the data it generally works well enough for most things.

Today I was working on a project that uses Twig. It's similar to Jekyll in many ways — as is Swig, which is probably why I like them both — but has a few differences here and there. One of those differences is the lack of these filters.

A quick Google search brought up this old Google Groups discussion along with the general documentation on loops. In rereading the documentation regarding the slice filter I realized you can emulate those filters quite elegantly!

To emulate Liquid's offset filter in Twig:

{% for item in group[1:] %}
{{ item.attribute }}
{% endfor %}

To emulate Liquid's limit filter in Twig:

{% for item in group[:1] %}
{{ item.attribute }} {% endfor %}

Obviously you can replace the number 1 in both examples with whatever you wish to offset or limit the group by.

Nice to know!