Consider this scenario: A site has multiple color schemes to reflect different brands (let's call them Alpha and Bravo) owned by the company. A given page should be able to reflect the scheme of whichever brand it's talking about.
Easy enough! We can put a taxonomy reference field on the page with our choice. Let's call the field field_brand. Then, we can preprocess the node to add a class name and/or CSS library to handle however the page needs to change.
/**
* Implements hook_preprocess_HOOK() for node templates.
*/
function mytheme_preprocess_node(&$variables) {
$node = $variables['node'];
$view_mode = $variables['view_mode'];
switch ($view_mode) {
case 'full':
// Check if the node has a brand field and the field has a value.
if (!empty($node->field_brand)) {
$brand_name = $node->field_brand->entity->name->value;
$brand_class = Html::cleanCssIdentifier(strtolower($brand_name));
$variables['attributes']['class'][] = 'brand-' . $brand_class;
$variables['#attached']['library'][] = 'mytheme/brand_' . str_replace('-', '_', $brand_class);
}
break;
}
}
If a brand is selected, we make a machine name from the taxonomy term name, then inject that as a class name for the node, and pull in a corresponding library in the theme. We can do whatever we want in the CSS and JS of that library to make the page look as desired.