diff --git a/core/lib/Drupal/Core/Template/TwigExtension.php b/core/lib/Drupal/Core/Template/TwigExtension.php index 8270c66..ed9ed3d 100644 --- a/core/lib/Drupal/Core/Template/TwigExtension.php +++ b/core/lib/Drupal/Core/Template/TwigExtension.php @@ -54,6 +54,13 @@ class TwigExtension extends \Twig_Extension { protected $dateFormatter; /** + * An empty attributes object that can be cloned. + * + * @var \Drupal\Core\Template\Attribute + */ + protected $attributes; + + /** * Constructs \Drupal\Core\Template\TwigExtension. * * @param \Drupal\Core\Render\RendererInterface $renderer @@ -135,6 +142,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 +608,25 @@ public function safeJoin(\Twig_Environment $env, $value, $glue = '') { }, (array) $value)); } + /** + * Creates an Attribute object. + * + * @param array $attributes + * An associative array of key-value pairs to be converted to attributes. + * + * @return \Drupal\Core\Template\Attribute + * An attributes object that has the given attributes. + */ + public function createAttribute(array $attributes = []) { + if (empty($attributes)) { + if (!$this->attributes) { + $this->attributes = new Attribute(); + } + + return clone $this->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..bbd22e2 100644 --- a/core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php +++ b/core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php @@ -299,6 +299,27 @@ public function testRenderVarWithGeneratedLink() { $this->assertEquals('', $result); } + /** + * @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']], + [], + [] + ]; + $result = $twig->render("{% for iteration in iterations %}{% endfor %}", ['iterations' => $iterations]); + $expected = '
'; + $this->assertEquals($expected, $result); + } + } class TwigExtensionTestString {