4. Use a node preprocess function to apply a class to nodes
In order to express our color choice in css, we will have to add a class to our node type based on the color field’s value. To do this, add this node preprocess function to your THEME.theme file:
use Drupal\Component\Utility\Html;
function THEME_preprocess_node(&$variables) {
$node = $variables['node'];
if ($node->hasField('field_color') && !$node->get('field_color')->isEmpty()) {
$color = $node->field_color->entity->getName();
$variables['attributes']['class'][] = Html::cleanCssIdentifier($color);
}
}
This block of code first checks to see if the node has the color field. If it does, it adds a class to the node that matches the value of the color selected.
Keep in mind, if you added the extra vocabulary from Step 2.5, your preprocess code would probably look more like this:
use Drupal\Component\Utility\Html;
function THEME_preprocess_node(&$variables) {
$node = $variables['node'];
if ($node->hasField('field_color_category') && !$node->get('field_color_category')->isEmpty()) {
$color = $node->field_color_category->entity->field_color->entity->getName();
$variables['attributes']['class'][] = Html::cleanCssIdentifier($color);
}
}
5. Apply CSS styles to your new color classes!
Using this newly applied color class, you can write the css needed to express each color. Because we are applying the class to the entire node and not just the field, we are able to apply unique color styles for each different content type and view mode. I love this technique because it allows for a lot of flexibility!