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


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:

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:

Tagged with: , ,
Posted in Development

Leave a Reply

Your email address will not be published. Required fields are marked *