Data attributes and feature flags

This commit is contained in:
Oliver Davies 2024-08-26 21:34:16 +01:00
parent 7a848be8a4
commit 4fdfe301d3

32
source/_notes/15.md Normal file
View file

@ -0,0 +1,32 @@
---
title: "Data attributes and feature flags"
date: 2024-08-26 21:34:15
tags: [Web Development, Software Development, Feature Flags, Drupal, CSS, PHP]
---
I recently used the [Feature Toggle module](https://www.drupal.org/project/feature_toggle) to set a data attribute which enabled some new styling for buttons.
## The PHP code
In the theme's .theme file:
```php
/**
* 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
```css
[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.