-
Drupal + Twig: Render Taxonomy Terms and Comma-Separated List
Here’s a snippet that renders the terms in a multi-value taxonomy reference field (in a node template) as plain text items separated by commas. Yes, you could get the string into the desired format using PHP, but I wanted to try to do it with only Twig. The result is moderately readable.
Twig Code:
For a taxonomy term reference field called field_pub_tr_res_committees
123456789101112<dt class="pub__rescomms">{% trans %}Research Committee(s){% endtrans %}</dt><dd class="pub__rescomms">{%- for item in content.field_pub_tr_res_committees['#items'] -%}{%- if loop.first -%}{{- item.entity.name.value -}}{%- elseif loop.last -%}{{- ' and ' ~ item.entity.name.value -}}{%- else -%}{{- ', ' ~ item.entity.name.value -}}{%- endif -%}{%- endfor -%}</dd>Output:
If 1 value: My first term