Problem/Motivation

In 8.x-1.1, we added a {% theme %} Twig tag and a theme() Twig function. Both of them create and render a render array. This makes 100% total sense for the tag, but not so much for the function.

Drupal extends Twig so that any variable printed is wrapped in Drupal's render_var() function, which converts render arrays to strings.

And that means we don't need to render the array inside theme(). If we have that function return the render array (without rendering it to a string, then when we print that data in a Twig file, it will still be rendered to a string properly by Drupal. That means we could alter the returned array with other filters or functions.

For example, you can use merge to alter the render array returned by theme():

  {{
    theme( 'item_list', {
      items: [
        'bee',
        'in',
        'my',
        'bonnet',
      ],
    })|merge({ '#attributes': { 'class': ['new-class'] } })
  }}

returns <ul class="new-class"><li>bee</li><li>in</li><li>my</li><li>bonnet</li></ul>

Proposed resolution

Remove the render method in Drupal\components\Template\TwigExtension and have Drupal\components\Template\TwigExtension::theme() return the array without rendering.

API changes

Drupal\components\Template\TwigExtension::theme() will return an array instead of a string.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

JohnAlbin created an issue. See original summary.

JohnAlbin’s picture

FileSize
1.8 KB

Patch.

JohnAlbin’s picture

Status: Active » Needs review
JohnAlbin’s picture

FileSize
3.84 KB

  • JohnAlbin committed 530f12e on 8.x-2.x
    Issue #3082816 by JohnAlbin: Make theme() function return render array
    
JohnAlbin’s picture

Status: Needs review » Fixed

Status: Fixed » Closed (fixed)

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