Advertising sustains the DA. Ads are hidden for members. Join today

Defining a new style

Last updated on
22 May 2025

To define a new style first in your custom module or theme you need to define a new yaml file custom_name.paragraphs.style.yml. Inside of this file you can define YAML configurations for all custom styles you need.

custom-style:
  title: 'Custom style'
  description: 'Short explanation of this style.'
  attributes:
    data-custom-attribute: some_value
  classes:
    - custom-css-class
    - custom-css-class--modifier
  groups:
    - custom_group
  libraries:
    - 'custom_module/custom_style'

Applying this 'Custom style' to some paragraph will add two CSS classes to it `custom-css-class custom-css-classs--modifier`, data attribute `data-custom-attribute: "some_value"` and will attach module library `custom_module/custom_style`.

Here we also defined that this 'Custom style' belongs to new style group `custom_group` which you need to define in `custom_module.paragraphs.style.group.yml` as:

custom_group:
  label: 'Custom group'

You can also reuse currently defined style groups from other active modules and themes which means you need to define a new style group only when you can not reuse existing style groups.

Adding custom attributes to your style

You can also use custom attributes in your style definition. For example in previous `custom_style` example you can do

custom_style:
  ...
  custom_attribute: some_value
  ...

And then in your code check you can check for this value. One way to do this is like:

/** @var \Drupal\paragraphs\ParagraphInterface $paragraph */
$paragraph = $variables['paragraph'];
// Does this paragraph has style plugin enabled.
if ($paragraph->getParagraphType()->hasEnabledBehaviorPlugin('style')) {
  // Get style plugin instance for this paragraph.
  $style_plugin = $paragraph->getParagraphType()->getBehaviorPlugin('style');
  // Get all plugin styles data for this paragraph.  
  $styles = $style_plugin->getStyles($paragraph);
  // Check if paragraph has button_size plugin with a value of button-width-full.
  if (isset($styles['custom_group'])) {
    $style = \Drupal::service('paragraphs_collection.style_discovery')->getStyle($$styles['custom_group']);
    if (!empty($style['custom_attribute'])) {
      // Do something...
    }
  }

Help improve this page

Page status: No known problems

You can: