Skip to content

Commit 60f55bd

Browse files
committed
Initial commit.
0 parents  commit 60f55bd

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# add-attributes-twig-extension
2+

add_attributes.function.php

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
<?php
2+
/**
3+
* @file
4+
* Add "add_attributes" function for Pattern Lab & Drupal
5+
*/
6+
7+
use Drupal\Core\Template\Attribute;
8+
9+
$function = new Twig_SimpleFunction('add_attributes', function ($context, $additional_attributes = []) {
10+
if (class_exists('Drupal')) {
11+
$attributes = new Attribute();
12+
13+
if (!empty($additional_attributes)) {
14+
foreach ($additional_attributes as $key => $value) {
15+
if (is_array($value)) {
16+
foreach ($value as $index => $item) {
17+
// Handle bem() output.
18+
if ($item instanceof Attribute) {
19+
// Remove the item.
20+
unset($value[$index]);
21+
$value = array_merge($value, $item->toArray()[$key]);
22+
}
23+
}
24+
}
25+
else {
26+
// Handle bem() output.
27+
if ($value instanceof Attribute) {
28+
$value = $value->toArray()[$key];
29+
}
30+
elseif (is_string($value)) {
31+
$value = [$value];
32+
}
33+
else {
34+
continue;
35+
}
36+
}
37+
// Merge additional attribute values with existing ones.
38+
if ($context['attributes']->offsetExists($key)) {
39+
$existing_attribute = $context['attributes']->offsetGet($key)->value();
40+
$value = array_merge($existing_attribute, $value);
41+
}
42+
43+
$context['attributes']->setAttribute($key, $value);
44+
}
45+
}
46+
47+
// Set all attributes.
48+
foreach($context['attributes'] as $key => $value) {
49+
$attributes->setAttribute($key, $value);
50+
// Remove this attribute from context so it doesn't filter down to child
51+
// elements.
52+
$context['attributes']->removeAttribute($key);
53+
}
54+
55+
return $attributes;
56+
}
57+
// Pattern Lab.
58+
else {
59+
$attributes = [];
60+
61+
foreach ($additional_attributes as $key => $value) {
62+
if (is_array($value)) {
63+
foreach ($value as $index => $item) {
64+
// Handle bem() output.
65+
if (strpos($item, $key . '=') !== FALSE) {
66+
parse_str($item, $result);
67+
// Remove the item.
68+
unset($value[$index]);
69+
// Strip surrounding quotes.
70+
$value[] = substr($result[$key], 1, -1);
71+
}
72+
}
73+
74+
$attributes[] = $key . '="' . implode(' ', $value) . '"';
75+
}
76+
else {
77+
// Handle bem() output.
78+
if (strpos($value, $key . '=') !== FALSE) {
79+
$attributes[] = $value;
80+
}
81+
else {
82+
$attributes[] = $key . '="' . $value . '"';
83+
}
84+
}
85+
}
86+
87+
return implode(' ', $attributes);
88+
}
89+
90+
}, array('needs_context' => true, 'is_safe' => array('html')));

0 commit comments

Comments
 (0)