diff --git a/core/lib/Drupal/Core/Template/TwigExtension.php b/core/lib/Drupal/Core/Template/TwigExtension.php index 8270c66..3fcbe2c 100644 --- a/core/lib/Drupal/Core/Template/TwigExtension.php +++ b/core/lib/Drupal/Core/Template/TwigExtension.php @@ -135,6 +135,7 @@ public function getFunctions() { new \Twig_SimpleFunction('attach_library', [$this, 'attachLibrary']), new \Twig_SimpleFunction('active_theme_path', [$this, 'getActiveThemePath']), new \Twig_SimpleFunction('active_theme', [$this, 'getActiveTheme']), + new \Twig_SimpleFunction('create_attribute', [$this, 'createAttribute']), ]; } @@ -600,4 +601,18 @@ public function safeJoin(\Twig_Environment $env, $value, $glue = '') { }, (array) $value)); } + /** + * Creates an Attribute object. + * + * @param array $attributes + * (optional) An associative array of key-value pairs to be converted to + * HTML attributes. + * + * @return \Drupal\Core\Template\Attribute + * An attributes object that has the given attributes. + */ + public function createAttribute(array $attributes = []) { + return new Attribute($attributes); + } + } diff --git a/core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php b/core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php index ea93703..10438c1 100644 --- a/core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php +++ b/core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php @@ -299,6 +299,33 @@ public function testRenderVarWithGeneratedLink() { $this->assertEquals('', $result); } + /** + * Tests creating attributes within a Twig template. + * + * @covers ::createAttribute + */ + public function testCreateAttribute() { + $renderer = $this->prophesize(RendererInterface::class); + $extension = new TwigExtension($renderer->reveal()); + $loader = new StringLoader(); + $twig = new \Twig_Environment($loader); + $twig->addExtension($extension); + + $iterations = [ + ['class' => ['kittens'], 'data-toggle' => 'modal', 'data-lang' => 'es'], + ['id' => 'puppies', 'data-value' => 'foo', 'data-lang' => 'en'], + [], + ]; + $result = $twig->render("{% for iteration in iterations %}{% endfor %}", ['iterations' => $iterations]); + $expected = '
'; + $this->assertEquals($expected, $result); + + // Test default creation of empty attribute object and using it's method. + $result = $twig->render(""); + $expected = '
'; + $this->assertEquals($expected, $result); + } + } class TwigExtensionTestString {