How do I add commas to an output that returns a list of names? 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
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 &gt; 1 %} and {% endif %}{{ name.title }}{%if i &gt; 2 and loop.index0 &lt; 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 ,