Problem/Motivation

Some effects and libraries need extra attributes that we need to add in order to work correctly.

Proposed resolution

Instead of doing that for each style separately, we could generalize that and send data attributes through the style discovery down to the templates to the attributes array.

Comments

sasanikolic created an issue. See original summary.

sasanikolic’s picture

StatusFileSize
new1.75 KB

Here is the patch with the paragraph preprocess.

sasanikolic’s picture

Status: Active » Needs review
berdir’s picture

Status: Needs review » Needs work
+++ b/paragraphs_collection.module
@@ -90,3 +91,29 @@ function paragraphs_collection_themes_uninstalled($themes) {
+ */
+function paragraphs_collection_preprocess_paragraph(array &$variables) {
+  /** @var ParagraphInterface $paragraph */
+  $paragraph = $variables['paragraph'];
+  $paragraph_styles = $paragraph->getBehaviorSetting('style', 'styles', FALSE);
+
+  $all_styles = \Drupal::service('paragraphs_collection.style_discovery')->getStyles();
+
+  if ($paragraph_styles) {
+    foreach ($paragraph_styles as $paragraph_style) {
+      if (array_key_exists($paragraph_style, $all_styles) && array_key_exists('attributes', $all_styles[$paragraph_style])) {
+        if (!empty($all_styles[$paragraph_style]['attributes'])) {
+          $style_attributes = $all_styles[$paragraph_style]['attributes'];
+          foreach ($style_attributes as $attribute) {
+            foreach ($attribute as $attribute_key => $attribute_value) {
+              $variables['attributes'][$attribute_key] = $attribute_value;
+            }
+          }
+        }
+      }

we can add it directly in the plugin, where we have all information already.

sasanikolic’s picture

Status: Needs work » Needs review
StatusFileSize
new2.88 KB
new1.13 KB

Here is the improved patch with the moved code to the plugin.

Is there a nicer way to flatten the attributes array? This code supports only one level of data-attributes for now. Do we need to support multiple levels?

sasanikolic’s picture

Sorry, that crazyness is not needed. I realized I was defining the attributes the wrong way in the yml file.
Attributes should be defined like this:

attributes:
  data-toc-depth: 1

Instead, I had the dash in front of data.

berdir’s picture

Status: Needs review » Needs work
Issue tags: +Needs tests

Yes, that looks good now, but we should have a test for this, extend one of the existing test styles with some attributes and assert they are added.

sasanikolic’s picture

Status: Needs work » Needs review
StatusFileSize
new1.27 KB
new2.06 KB

I added a small test here.

berdir’s picture

Status: Needs review » Fixed

Nice.

  • Berdir committed 8ea3eb8 on 8.x-1.x authored by sasanikolic
    Issue #3040565 by sasanikolic: Attach data attributes through styles
    
berdir’s picture

Status: Needs review » Fixed

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.