Skip to content

Title and content attributes addition #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,17 @@ Can also be used with the [bem function](https://github.com/drupal-pattern-lab/b

<div {{ add_attributes(additional_attributes) }}></div>
```

Can also be used with title_attributes or content_attributes:
```
{% set additional_title_attributes = {
"class": ["foo__title", "bar__title"],
} %}
{% set additional_content_attributes = {
"class": ["foo__content", "bar__content"],
} %}

<h2 {{ add_attributes(additional_title_attributes,'title_attributes') }}></h2>
<div {{ add_attributes(additional_content_attributes,'content_attributes') }}>

```
16 changes: 10 additions & 6 deletions add_attributes.function.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@

use Drupal\Core\Template\Attribute;

$function = new Twig_SimpleFunction('add_attributes', function ($context, $additional_attributes = []) {
$function = new Twig_SimpleFunction('add_attributes', function ($context, $additional_attributes = [], $attribute_type = 'attributes') {
if (!in_array($attribute_type, ['attributes','title_attributes','content_attributes'])) {
throw new Exception('Invalid attribute type.');
}

if (class_exists('Drupal')) {
$attributes = new Attribute();

Expand Down Expand Up @@ -35,21 +39,21 @@
}
}
// Merge additional attribute values with existing ones.
if ($context['attributes']->offsetExists($key)) {
$existing_attribute = $context['attributes']->offsetGet($key)->value();
if ($context[$attribute_type]->offsetExists($key)) {
$existing_attribute = $context[$attribute_type]->offsetGet($key)->value();
$value = array_merge($existing_attribute, $value);
}

$context['attributes']->setAttribute($key, $value);
$context[$attribute_type]->setAttribute($key, $value);
}
}

// Set all attributes.
foreach($context['attributes'] as $key => $value) {
foreach($context[$attribute_type] as $key => $value) {
$attributes->setAttribute($key, $value);
// Remove this attribute from context so it doesn't filter down to child
// elements.
$context['attributes']->removeAttribute($key);
$context[$attribute_type]->removeAttribute($key);
}

return $attributes;
Expand Down