Fix aria-label generated by colorbox

Created on 15 May 2025, 3 days ago

Problem/Motivation

Colorbox module incorrectly generates aria-label eg:

aria-label="{"alt":"Some image alt description."}"

aria-label should be simple text not JSON:
aria-label="Some image alt description."

Proposed resolution

diff -Eupr colorbox.theme.old.inc colorbox.theme.inc
--- colorbox.theme.old.inc      2025-05-15 12:02:37.267158077 +0200
+++ colorbox.theme.inc  2025-05-15 12:17:05.530368950 +0200
@@ -145,7 +145,19 @@ function template_preprocess_colorbox_fo
   $variables['image']['#attributes']['id'] = $unique_id;
   if (!empty($data_cbox_img_attrs)) {
     $variables['attributes']['data-cbox-img-attrs'] = '{' . implode(',', $data_cbox_img_attrs) . '}';
+    // Add aria-label based on alt or title.
+    $img_attrs = [];
+    foreach ($data_cbox_img_attrs as $attr) {
+      if (strpos($attr, '"alt":') === 0) {
+        $img_attrs['alt'] = trim(substr($attr, 6), '"');
+      }
+      elseif (strpos($attr, '"title":') === 0) {
+        $img_attrs['title'] = trim(substr($attr, 8), '"');
+      }
+    }
+    $variables['attributes']['aria-label'] = $img_attrs['alt'] ?? $img_attrs['title'] ?? '';
   }
+  $variables['attributes'] = new Drupal\Core\Template\Attribute($variables['attributes']);
 }

 /**
diff -Eupr templates/colorbox-formatter.html.old.twig templates/colorbox-formatter.html.twig
--- templates/colorbox-formatter.html.old.twig  2025-05-15 12:05:15.100536605 +0200
+++ templates/colorbox-formatter.html.twig      2025-05-15 12:07:14.443175824 +0200
@@ -14,4 +14,4 @@
  */
 #}

-<a href="{{ url }}" aria-label="{{ attributes['data-cbox-img-attrs']|raw }}" role="button" {{ attributes }}>{{ image }}</a>
+<a href="{{ url }}" aria-label="{{ attributes['aria-label'] }}" role="button" {{ attributes }}>{{ image }}</a>
🐛 Bug report
Status

Needs review

Version

2.1

Component

Code

Created by

🇵🇱Poland lordzik

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024