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
1 2 3 4 5 6 7 8 9 10 11 12 |
<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
If 2 values: My first term and My second term
If 3+ values: My first term, My second term, My third term and My fourth term
Alternative Output:
If you prefer a comma before the and when there are 3+ values, use this code instead:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<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 loop.length == 2 -%} {{- ' and ' ~ item.entity.name.value -}} {%- elseif loop.last -%} {{- ', and ' ~ item.entity.name.value -}} {%- else -%} {{- ', ' ~ item.entity.name.value -}} {%- endif -%} {%- endfor -%} </dd> |
Additional Notes:
You have to use Twig’s whitespace modifiers to get the desired spacing.
I attempted to use {% spaceless %} around the <dd> tag but it did not help. It wasn’t until I added the hyphens to every Twig tag that the desired output was achieved.
Without the whitespace modifiers the output looks like this:
With the whitespace modifiers the output looks like this:
One Comment
schnippy
Thanks – this was exactly what I needed. I modified it a bit to add links to the term pages and posted this here:
https://gist.github.com/schnippy/3f53fe2ac5c847bed26e808d42210feb