Add CSS Classes using a select list field easily in Drupal 8 Twig Templates

Published by Kerry
on June 13th, 2016

Using fields and a little twig, you can assign class wrappers to any other field you like.  For this example, we are going have a paragraph type called Image (machine name pa_im), and within that paragraph type, we will create 2 fields.  One is called Image with the machine name of field_im, and the other is a list text type field called field_st, with the following allow values.  In addition for the field_st, on the Manage Display page, you will need to set the field to display as a Key.

Drupal field list

Now that your paragraph fields are ready to go, within your content, upload an image within the paragraph field and choose your image style from the dropdown.  

Utilizing twig in the paragraph template itself, we can simply use:

<div class="{{ content.field_st[0] }}">{{ content.field_im }}</div>

At this point, when you inspect your code, you should see your image is now wrapped in a container div that shows which style you chose in the dropdown, and you can style your content based on those available values.  The beauty of this is you don’t need functions.  Just straight Twig.

Add your css, such as;


div.image-body {
float: left;
width: 66%;
}

And you are good to go!