Skip to content

Instantly share code, notes, and snippets.

@laradevitt
Created May 1, 2021 01:05
Show Gist options
  • Save laradevitt/2b185a9ee3cc2ccfe17d92097011a6ea to your computer and use it in GitHub Desktop.
Save laradevitt/2b185a9ee3cc2ccfe17d92097011a6ea to your computer and use it in GitHub Desktop.
(Drupal 8) Add attribute aria-describedby to responsive image in Twig template.
<?php
/**
* Implements hook_preprocess_node__HOOK().
*
* (a11y) Pass the media target_id to the template so we can use it to form
* a unique id to target from aria-describedby attribute.
*/
function MYTHEME_preprocess_node__slide(array &$variables) {
$node = $variables['node'];
$image = $node->get('field_image_media')->getValue();
$media_entity = $node->get('field_image_media')->first()->get('entity')->getTarget()->getValue();
$variables['image_target_id'] = $media_entity->get('field_media_image')->target_id;
}
{#
/**
* @file
*/
#}
{# (a11y) Taking a different approach so we can add `aria-describedby` attribute
to the <img> tag. Note: `file_uri` function is provided by twig_tweak module. #}
{% set image_uri = node.field_image_media|file_uri %}
{%
set responsiveImage = {
'#theme': 'responsive_image',
'#responsive_image_style_id': 'slide',
'#uri': image_uri,
'#attributes': { width: '1040', height: '585', alt: '', 'aria-describedby': 'description-' ~ image_target_id },
}
%}
<article{{ attributes.addClass('node').removeAttribute('role') }}>
{{ title_prefix }}
{% if label and not page %}
<h2{{ title_attributes }}>
<a href="{{ url }}" rel="bookmark">{{ label }}</a>
</h2>
{% endif %}
{{ title_suffix }}
{% if display_submitted %}
<footer>
{{ author_picture }}
<div{{ author_attributes }}>
{% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
{{ metadata }}
</div>
</footer>
{% endif %}
<div{{ content_attributes }}>
{# Render the responsive image. #}
{{ responsiveImage }}
{# A field has been added to the content type to contain a long
description for screen readers. #}
<div class="visually-hidden" id="description-{{ image_target_id }}">{{ node.field_image_description.value }}</div>
{# Render the rest of the content without the fields above. #}
{{ content|without('field_image_media', 'field_image_description') }}
</div>
</article>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment