Drupal integration for studiometa/twig-toolkit: Twig helpers for HTML classes, attributes, and inline styles, plus a Drupal-aware html_element tag that works with core Attribute objects.

Machine name: twig_toolkit. No configuration UI - enabling the module registers the Twig extension.

Features

  • Twig extension - Studio Meta functions and filters in Drupal Twig.
  • html_element tag - accepts core Attribute (via toArray()), arrays, or hashes.
  • Thin layer - wraps the MIT upstream library; does not reinvent the helpers.

Functions: html_classes(), html_styles(), html_attributes(), merge_html_attributes(), twig_toolkit_url().

Filter: twig_toolkit_without.

Post-Installation

  1. composer require drupal/twig_toolkit
  2. drush en twig_toolkit -y then drush cr
  3. Use the helpers in theme Twig templates.

Example - classes and attributes

{% set classes = html_classes([
  'button',
  { 'button--primary': is_primary },
]) %}
{% set attrs = {
  class: classes,
  data_component: 'Button',
} %}
<button {{ html_attributes(attrs) }}>
  {{ 'Click me'|t }}
</button>

Example - html_element with Drupal Attribute

{% set attributes = attributes.addClass(
  'block',
  'block--featured'
) %}
{% html_element 'section' with attributes %}
  {{ content }}
{% end_html_element %}

Optional with ... argument: Drupal Attribute, array, or hash.

Additional Requirements

Similar projects

Integration layer around studiometa/twig-toolkit. Prefer core Attribute alone when you only need addClass() / setAttribute().

Supporting this Module

Issue queue for bugs and feature requests.

Community Documentation

Full API and more examples: README on git.drupalcode.org.

Supporting organizations: 

Project information

Releases