1

Who can tell me how to create a pager on craft CMS. How would I implement this:

{% set games = craft.entries().section('games').limit(10).all() %}

I was thinking of getting the page number from the URL. By dividing the total number of elements by the number of output elements, determine the number of pages. Well, using .limit() to output the elements of the requested page, for example:

{% set games = craft.entries().section('games').limit(10,20).all() %}

But as I understand it, only one number is specified in .limit() and that's it. Is there a method in Craft CMS that allows you to output limited entries in the "FROM - TO" model? Maybe it would help me a lot

1 Answer 1

3

You’re looking for the {% paginate %} tag!

This will take care of reading the "page" out of your URL, based on the pageTrigger config setting and setting the query’s offset:

{# Set up your query, but don't execute it: #}
{% set gamesQuery = craft.entries()
  .section('games')
  .limit(10) %}

{# Pass the query to the tag and let Craft handle setting the `offset`: #}
{% paginate gamesQuery as games, pageInfo %}

<ul>
  {% for game in games %}
    <li>{{ game.getLink() }}</li>
  {% endfor %}
</ul>

Note that limit here is still applied, and is responsible for setting the number of results per "page."

Check out the official documentation (linked above) for more info—and to learn about outputting links to other pages of results!


To answer your second question more directly: Yes—element queries also support the .offset() param, which will return results beginning at that index. Combined with .limit(), you can effectively select a range of elements, where offset is the start and offset + limit (pseudo-code) is the end. This is what makes the paginate tag work, under the hood—but you don't need to worry about the minutiae. 😉

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.