Chris vCB
Chris vCB

Reputation: 1053

Getting penultimate element in a Jinja2 iteration

Let lst be a Listof vegetables represented as strings: ["cucumbers", "peppers", "tomatoes", "carrots"]. I wish to join these with commas, except that I wish the last to be the word and instead (for the purpose of this exercise, let's assume a degree tolerance for the Oxford comma), to get the following:

cucumbers, peppers, tomatoes, and carrots

How would I go about accomplishing this in Jinja2? I know loop.last lets me identify the last, but not the penultimate iteration, which is where this would be relevant.

Upvotes: 2

Views: 290

Answers (3)

Phil Gyford
Phil Gyford

Reputation: 14644

For those who don't want the Oxford comma, I've used this:

{% for name in my_list %}
  {{ name }}
  {%- if loop.length > 1 and not loop.last -%}
    {%- if loop.revindex0 == 1 %} and {% else %}, {% endif %}
  {% endif %}
{% endfor %}

Outputs something like:

cucumbers, peppers, tomatoes and carrots

Upvotes: 0

Animesh D
Animesh D

Reputation: 5002

I have achieved the oxford comma by doing this:

{% for label in post.labels %}
    <li><a href="/labels/{{label}}">{{label}}</a>
    {% if not loop.last and loop.length > 2%}, {%endif%}
    {% if loop.revindex0 == 1 %} and{%endif%}</li>
{% endfor %}

Upvotes: 0

techraf
techraf

Reputation: 68609

{% if loop.revindex == 2 %}

Or

{% if loop.revindex0 == 1 %}

See for-loop variables in the List of Control Structures chapter.

Upvotes: 1

Related Questions