1

I have a simple for loop to get the names of countries from a category.

{% for name in country %} {{ name.title }} {% endfor %}  

The output is typically returns the name of 1 country. But, some entries are associated with more than one country.

For example:

Belgium Czech Republic Denmark Greece Netherlands Norway Portugal

How do I template for an entry that returns 2-N country names by adding "," between each country and "and" before the last country?

This is what I want to output:

Belgium, Czech Republic, Denmark, Greece, Netherlands, Norway and Portugal

1

You can use loop variables

{% set i = country|length %} // number of total items
{% set indexLast = i - 2 %}  // index of the last comma
{% for name in country %}
    {% if loop.last and i > 1 %} and {% endif %}{{ name.title }}{%if i > 2 and loop.index0 < indexLast  %},{% endif %}
{% endfor %}

Explanation:

  • if there is more than one item and it is the last iteration: add an and at the beginning
  • if there are more than 2 items (otherwise it's only one and) and the current loop index is smaller than count - 2 ( it should display nothing in the last iteration and only an and before the last)-> display a comma ,
  • Unexpected token "name" of value "last" ("end of statement block" expected).. – Hellyar Jun 4 '18 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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