pallets / jinja

A very fast and expressive template engine.

Home Page:https://jinja.palletsprojects.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add a simple "next" filter to retrieve the next item in an iterator

n-borges opened this issue · comments

I recently found myself in a similar usecase:

# original file
long list of similar lines with a difference -- 123 -- and a value to increment: X
long list of similar lines with a difference -- 321 -- and a value to increment: X
long list of similar lines with a difference -- 456 -- and a value to increment: X
long list of similar lines with a difference -- 654 -- and a value to increment: X
# ...and so on

I had to replace the "X"s in the file with some values, which i had in a list. in this case, using a for-loop is a non-viable option, since the lines to produce are not equal and contain not predictable values. I mean, it could be done by extracting those values and parametrizing them as well, using zip or whatever, but I think it would be more straightforward in such a scenario to simply call next on the iterator and calling it a day.

# template using sequence indexing (not what i'd like)
long list of similar lines with a difference -- 123 -- and a value to increment: {{ my_list[0] }}
long list of similar lines with a difference -- 321 -- and a value to increment: {{ my_list[1] }}
long list of similar lines with a difference -- 456 -- and a value to increment: {{ my_list[2] }}
long list of similar lines with a difference -- 654 -- and a value to increment: {{ my_list[3] }}
# ...and so on

# template calling "next" (that's the feature I would like and that I cannot find in the docs)
long list of similar lines with a difference -- 123 -- and a value to increment: {{ my_generator | next }}
long list of similar lines with a difference -- 321 -- and a value to increment: {{ my_generator | next }}
long list of similar lines with a difference -- 456 -- and a value to increment: {{ my_generator | next }}
long list of similar lines with a difference -- 654 -- and a value to increment: {{ my_generator | next }}
# ...and so on

What do you think? I know one can always write its own filters, but for such a basic task it may be worth to add this to the built in ones.
I could write the filter and a couple tests for a PR.

Thanks!

env.filters["next"] = next