Joining Strings in a Drupal Views Field using Twig

I have two optional fields on a Drupal 8 content type: City and State. Both are rendered as simple text.

In a fields-based View I wanted to show the field output as “Portland” or “Portland, OR”, or “OR”.

First, I added the two fields, State then City (the order is important). Next I excluded the State field from display.

Finally, I opened the Rewrite Results pane of the City field and checked the Override the output of this field with custom text checkbox.

After several attempts at using Twig’s joinreplacespaceless, and more, I landed on this simple solution as the rewrite text:

Note the whitespace modifiers (hyphens). These are the key to getting  Portland, OR  instead of   Portland , OR .

Also, we cannot just use  {{field_member_city}}, {{field_member_state}} because we could end up with  , OR if City is empty.

Tagged with: , , ,
Posted in Development

Leave a Reply

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

*