Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

limit tag in for loops #504

Closed
ThanosFisherman opened this issue Apr 25, 2020 · 5 comments
Closed

limit tag in for loops #504

ThanosFisherman opened this issue Apr 25, 2020 · 5 comments

Comments

@ThanosFisherman
Copy link

Hi,

is there a limit tag like there is in Liquid templating that would allow me to exit a loop at specified index?

What I want:

 {% for item in numbers limit:4 %}
    {{ item }}
  {% endfor %}

How I worked this around

 {% for item in numbers %}
   {% if loop.index <= 3 %}
      {{ item }}
   {% endif %}
 {% endfor %}

But my solution is too verbose and I don't like it. Any suggestions? Furthermore I'd enjoy having more tags like this for example offset maybe break or continue as well as ranges.

Am I asking for too much for a template language?

@cjbrooks12
Copy link
Contributor

Slice should help https://pebbletemplates.io/wiki/filter/slice/

@ThanosFisherman
Copy link
Author

Slice works great if you already know the length of an array you are about to slice. But if you enter a number bigger than the array length in toIndex parameter then you get

.PEB Syntax Error: toIndex must be smaller than input size: 3

in contrast with limit which will give you what's already available up until the limit number. Therefore in my case if the array length is smaller than 4, limit would give me all the array elements.

My use case is to display the 4 most recent posts in my orchid website and my solution works but I was just wondering if there's something more idiomatic.

@ebussieres
Copy link
Member

I think that we can change slice and take the collection size when the toIndex is greater than the collection size. That way, you can achieve what you want.

What do you think ?

@ThanosFisherman
Copy link
Author

Yes that would work great for my case I think. Should you prefer to modify the slice operator instead of creating a new one, that I leave it up to you :)

@ebussieres
Copy link
Member

Fix's gonna be available in next release

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants