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!

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

A quick Drupal 8 tutorial that covers how to use a select field to add CSS classes in a twig template.  We use this technique often on Paragraph entities where we need to position, or color using CSS.

Work with Xeno Media

We know you'll judge us by the company we keep. That's just the way we like it. We would love to hear from you. If you would like to discuss your project, please call us at 630.599.1550 or fill out our Contact Form.

Contact Us

18W100 22nd Street
Suite 128
Oakbrook Terrace, IL 60181
630.599.1550 View Map

Signup for our Newsletter!