Using a field value as Twig attribute I need to set a field value as CSS class in a page template. How can I do it the Twig way?

{{attributes.addClass('class-name')}} is the way to set the class manually.

I have a list field to let the user set a background color for a part of the site. In Drupal 7 I used this code.

&lt;div class="&lt;?php print render($content['field_background']); ?&gt;"&gt;


In Drupal 8, I can print the field with {{ content.field_background }}, but &lt;div class="{{ content.field_background }}"&gt; doesn't work.
This can be done in a few ways, you can do it all in the node template with Twig or you can create a preprocess function and create a variable for use in the node template. The key to learning what is in the array is to use Devel Kint. Without that, you won't know what is in the array. 

First install Kint which comes with the Devel module for Drupal 8. Next, pick your node template (but this can be done in any kind of template) and examine the content variable like so (ideally at the bottom of the template).

{{ kint (content) }}




From this, we get debugging info printed on the page and if you expand the array, you'll see a whole slew of information. Right away, I see my background value and I can construct a path to print this out as

{{ content.field_background[0]['#markup'] }}


Now you can print this as a background style or class in a div

&lt;div style="background-color: {{ '#' }}{{ content.field_background[0]['#markup'] }};" class="color-{{ content.field_background[0]['#markup'] }}"&gt;
&lt;h2&gt;Hello&lt;/h2&gt;
&lt;/div&gt;


I've tested this ands it works great, the div rendered the background color I had selected in my field list on node edit. 

Now this is not ideal so we probably want to create a variable for this in a preprocess_node in our theme's .theme file. 

function MYTHEME_preprocess_node(&amp;$vars) {
  $vars['bgcolor'] = '#' . $vars['content']['field_background'][0]['#markup'];
}


Now that I have a var created, it's much cleaner to print this out:

 &lt;div style="background-color: {{ bgcolor }};" &gt;
      &lt;h2&gt;Hello&lt;/h2&gt;
    &lt;/div&gt;


One note for above, you should probably wrap this with an if statement to check if it's empty or not. 

This would work or structure the if statement where you like it

   {% if bgcolor %}
    &lt;div style="background-color: {{ bgcolor }};" &gt;
      &lt;h2&gt;Hello&lt;/h2&gt;
    &lt;/div&gt;
    {% endif %}