Skip to content

Commit e352a3d

Browse files
author
Daniel Morse
committed
feat: add merge_attributes() function to TwigFunctions, make available in twig templates.
1 parent e1bd40b commit e352a3d

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

packages/core-php/src/TwigExtensions/BoltExtras.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ public function getFunctions() {
2020
Bolt\TwigFunctions::link(),
2121
Bolt\TwigFunctions::getSpacingScaleSequence(),
2222
Bolt\TwigFunctions::github_url(),
23-
Bolt\TwigFunctions::inlineFile()
23+
Bolt\TwigFunctions::inlineFile(),
24+
Bolt\TwigFunctions::merge_attributes()
2425
];
2526
}
2627

packages/core-php/src/TwigFunctions.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,23 @@ public static function create_attribute() {
265265
});
266266
}
267267

268+
// Custom function for merging Drupal Attribute objects
269+
// Gives $source preference, unless a key is set in both arrays and $source value is empty or null
270+
public static function merge_attributes() {
271+
return new Twig_SimpleFunction('merge_attributes', function($target, $source) {
272+
// For each key in $source...
273+
foreach ($source as $key => $value) {
274+
// If $key is not in $target, or if $key is in $target and $value in $source is empty, add/overwrite $key in $target
275+
// NOTE: empty() and is_null() do not work in the second half of this statement. Why is that?
276+
if (empty($target[$key]) || (!empty($target[$key]) && $value != "")) {
277+
$target[$key] = $value;
278+
}
279+
}
280+
281+
return $target;
282+
});
283+
}
284+
268285
public static function github_url() {
269286
return new Twig_SimpleFunction('github_url', function(\Twig_Environment $env, $twigPath) {
270287
$filePath = TwigTools\Utils::resolveTwigPath($env, $twigPath);

0 commit comments

Comments
 (0)