Fatal error when using a Twig defined variable as Attribute value

Created on 24 July 2025, 2 months ago

Problem/Motivation

Twig allows to create variables inside the templates using the set command. When one of these variables is used as an Attribute, the rendering of this attribute throws the following error:
Error: Call to undefined method Twig\Markup::render() in Drupal\Core\Template\Attribute->__toString() (line 329 of core/lib/Drupal/Core/Template/Attribute.php)

Steps to reproduce

Add this code into one of your twig templates (eg. page.html.twig)

  {% set test_attr %}
    This is a test
  {% endset %}
  {%
    set attributes = create_attribute()
     .setAttribute('data-test', test_attr)
  %}
  {{ attributes }}

Expected result would be to display data-test="This is a test".
Current result is a fatal error.

Proposed resolution

In \Drupal\Core\Template\Attribute::createAttributeValue(), expand the condition on instances of MarkupInterface to be true on instances of \Stringable objects.

🐛 Bug report
Status

Active

Version

11.0 🔥

Component

theme system

Created by

🇫🇷France duaelfr Montpellier, France

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

Merge Requests

Comments & Activities

Production build 0.71.5 2024