43 lines
1.4 KiB
Markdown
43 lines
1.4 KiB
Markdown
---
|
|
title: CSS, data attributes and feature flags
|
|
date: 2024-08-25
|
|
permalink: daily/2024/08/25/css--data-attributes-and-feature-flags
|
|
tags:
|
|
- software-development
|
|
- drupal
|
|
- php
|
|
- feature-flags
|
|
- css
|
|
- drupal-planet
|
|
cta: ~
|
|
snippet: |
|
|
How I combined a feature flag and a data attribute to release some new CSS styles to a project.
|
|
---
|
|
|
|
I recently used [Drupal's Feature Toggle module](https://www.drupal.org/project/feature_toggle) to set a data attribute which enabled some new styling for buttons.
|
|
|
|
Firstly, within the theme's .theme file, I added this code:
|
|
|
|
```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, it adds a `data-use-new-button-styles=""` attribute to the `body` element.
|
|
|
|
If it is disabled, the attribute is not added, so I can write CSS that's applied when the data attribute is present:
|
|
|
|
```css
|
|
[data-use-new-button-styles] .btn-primary {
|
|
background-color: red;
|
|
}
|
|
```
|
|
|
|
In a Tailwind CSS project (this isn't), the same could be achiveable with a custom interaction state - similar to `hover`, `focus` and `active`. Something like `new-button-styles:bg-red-500`.
|
|
|
|
I like using feature flags and was happy to find a way to use them when adding this new CSS.
|