ifusion
ifusion

Reputation: 2233

How to set only an offset when looping?

I have a situation where I need to start to loop through my images from the 7th image onwards e.g

// This shows the first 6 images

<% loop $GalleryImages.Limit(6) %>

    <img src="$Image">

<% end_loop %>

--

Then I need to show from the 7th image on wards. We can use the offset here but we have to set a limit (first parameter)

<% loop $GalleryImages.Limit(100, 6) %>

    <img src="$Image">

<% end_loop %>

Is there a way to just set the offset only or maybe another way I should tackle this?

Upvotes: 2

Views: 363

Answers (2)

UncleCheese
UncleCheese

Reputation: 1584

The cleanest thing to do is to create a method in your controller or model that runs the query.

public function OtherGalleryImages()
{
  return $this->GalleryImages()->limit(null, 6);
}

But I would question whether you really ever want to run an unlimited query, and for that reason, I think a simpler fix would be to just add a reasonable number into your limit on the template, as you have done. If you ever have more than 100, perhaps you have bigger problems than the expressiveness of your template syntax. :-)

Upvotes: 5

BenG
BenG

Reputation: 1766

PHP's array_slice method allows you to specify a start, without know the length of the array. http://php.net/manual/en/function.array-slice.php

The advantage of using slice is that if the array is too short or too long, it will return an empty array instead of null, thus avoid errors

Upvotes: -3

Related Questions