Create a comma-separated list from a Multi-Value field in Drupal 8
Here’s an example of how to create a comma-separated list from a multi-value field in Drupal 8 via a theme template.
There may be Drupal 8 modules that do this for you, but I haven’t been able to figure out how to do this with default Drupal 8 or Display Suite. So I implemented it in my sub-theme.
Example Use Case
I have a People content type. It has a multi-value field to add a position or positions. The design wants to display them in a comma-separated inline list.
Strategy
Create a custom theme template for that individual field for the purpose of modifying the default HTML. If we were planning to do this with many fields, I might be investigating a more re-usable solution like a module. But this is likely a one-off.
1. Create the template
I want to override the default template for my multi-value field which in my case was the field.html.twig
template in my base theme. I will duplicate that file into my subtheme’s templates folder and use Twig Debugging tools to find out what to name the template. In my case: field--field-people-position.html.twig
2. Looking at the template
The template covers four scenarios with if
statements.
- Single-value field with the label hidden
- Multi-value field with the label hidden
- Single-value field with the label shown
- Multi-value field with the label shown
I’m going to set up comma-separated ul
for the two multi-value field scenarios.
3. The code
Here’s the key snippet:
{% for item in items %}
{% if loop.last %}
{% set separator = '' %}
{% else %}
{% set separator = ', ' %}
{% endif %}
<li{{ item.attributes}}>
{{ item.content }}{{ separator }}
</li>
{% endfor %}
This sets a variable we called separator
(but could be anything). loop.last
is a Twig special variable that looks for the last item in the list. So here, if the item is the last in the list, the separator is nothing. But if it’s not last, then it’s a ,
(comma and a space). Now that you have defined a variable you can print it with {{ separator }}
right after the item.