Quantcast
Channel: Issues for Drupal core
Viewing all articles
Browse latest Browse all 295818

Create twig |as filter

$
0
0

Background

In https://www.lullabot.com/articles/level-your-twiggery, @hawkeye.twolf laid out a method for creating an |as() twig filter that "adds template suggestions to a render array"

With this, the Twig code for wrapping the body field in a <details> element can be shortened to just {{ content.body|as('details') }}, along with a new template, field--details.html.twig, that adds the <details> markup. “How is this different/better” you might be asking “than just using the standard field-name template suggestion, field--node--body--article?” Three main reasons:

  1. Naming the template in a generic way leaves it available for use by other fields. If you have another field that needs the same customization, you no longer have to resort to various forms of chicanery, like copy/pasting the original template into an exact but renamed duplicate, Twig extendsing an otherwise-unrelated file, or symlinking one template to another.
  2. For experienced Drupal developers, the idea of template suggestions and their naming scheme might seem obvious. But to an outsider reviewing the Article’s node template, the source of the <details> wrapper around the body field may prove arcane. The addition of |as('details') makes the code more readable and adds semantic meaning to the source.
  3. Keeps front-end logic in the front-end. Normally, you would implement hook_theme_suggestions_alter() in a theme or module file to make unrelated fields use the same template. While there’s nothing wrong with this approach, it creates a dependency on PHP skills for any developer wishing to work on the front-end. The |as filter allows front-end developers to stay out of the PHP if they want to.

Task

I'd like to move this filter into Drupal core!

Discussion

I've discussed this with the @lauriii. He seemed excited about getting this in, and doesn't anticipate this being unrealistic for Drupal 10. I've also talked to @hawkeye.twolf, who said he has some updated code samples and seems willing to help!

Lets do this! ⚡️


Viewing all articles
Browse latest Browse all 295818

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>