From 4fdfe301d3f1c771a8f551578b2e7d3c95680255 Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Mon, 26 Aug 2024 21:34:16 +0100 Subject: [PATCH] Data attributes and feature flags --- source/_notes/15.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 source/_notes/15.md diff --git a/source/_notes/15.md b/source/_notes/15.md new file mode 100644 index 0000000..3ff7ee7 --- /dev/null +++ b/source/_notes/15.md @@ -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.