Skip to content
This repository was archived by the owner on May 13, 2026. It is now read-only.

Creates add_attribute twig function#10

Open
waako wants to merge 2 commits into
pattern-lab:masterfrom
waako:create_attribute
Open

Creates add_attribute twig function#10
waako wants to merge 2 commits into
pattern-lab:masterfrom
waako:create_attribute

Conversation

@waako

@waako waako commented Mar 19, 2018

Copy link
Copy Markdown

Replicates the Drupal twig function create_attribute for patternlab
https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates#create_attribute

#8 got me thinking about this, so used existing link twig function to make create_attribute work in Pattern Lab.
Tested locally with:

<p{{ create_attribute({'class': ['paragraph', 'text']}) }}>{{ content }}</p>

which results in generated html:

<p class="paragraph text">Test paragraph content</p>

@waako waako mentioned this pull request Mar 19, 2018
@waako

waako commented Mar 19, 2018

Copy link
Copy Markdown
Author

Needs improving to work with any attribute though

@waako

waako commented Mar 20, 2018

Copy link
Copy Markdown
Author

Function now loops through all the attributes

@piouPiouM

Copy link
Copy Markdown

Hi @waako,

I used the following to rely on Drupal's tools:

<?php
/**
 * @file
 * Add "create_attribute" function for Pattern Lab.
 */

use \Drupal\Core\Template\Attribute;

$function = new Twig_SimpleFunction('create_attribute', function ($attributes = []) {
  return new Attribute($attributes);
});

@sghoweri

sghoweri commented Jul 6, 2018

Copy link
Copy Markdown

@piouPiouM @waako

We do something virtually identical in our design system in order to make sure all of Drupal’s attributes functionality makes it in there (including the setAttribute, addClass, and removeClass methods, etc)

https://github.com/bolt-design-system/bolt/blob/master/packages/core-php/src/TwigFunctions.php#L240

use \Drupal\Core\Template\Attribute;

//...

// Backport the native create_attribute function from Drupal to natively work in Pattern Lab
  public static function create_attribute() {
    return new Twig_SimpleFunction('create_attribute', function($attributes) {
      return is_array($attributes) ? new Attribute($attributes) : $attributes;
    });
  }

@waako

waako commented Jul 18, 2018

Copy link
Copy Markdown
Author

@piouPiouM @sghoweri Thanks, that seems to make sense, did not realise that could use a Drupal class inside patternlab function.

@kristiaanvandeneynde

Copy link
Copy Markdown

Any way I can include this in my project already? The fix mentioned by sghoweri?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants