Data attributes and feature flags

I recently used the Feature Toggle module to set a data attribute which enabled some new styling for buttons.

The PHP code

In the theme's .theme file:

/**
* Implements hook_preprocess_html().
*/
function mytheme_preprocess_html(array &$variables): void {
$variables['attributes']['data-use-new-button-styles'] = \Drupal::service('feature_toggle.feature_status')->getStatus('use_the_new_button_styling');
}

If the feature toggle is enabled, this adds a data-use-new-button-styles="" attribute to the body element.

The CSS code

[data-use-new-button-styles] .btn-primary {
background-color: red;
}

I like using feature flags and was happy to find a way to use them for adding this new CSS.