Commit 99a55f04 authored by Cottser's avatar Cottser

Issue #2616756 by Charlotte17, joelpittet, lauriii, heddn, ytl, T'Bell...

Issue #2616756 by Charlotte17, joelpittet, lauriii, heddn, ytl, T'Bell Hernandez, Cottser, vaplas, alexpott: Allow instantiating Attribute objects within Twig
parent 4f6dc7bb
......@@ -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);
}
}
......@@ -299,6 +299,33 @@ public function testRenderVarWithGeneratedLink() {
$this->assertEquals('<a href="http://example.com"></a>', $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 %}<div{{ create_attribute(iteration) }}></div>{% endfor %}", ['iterations' => $iterations]);
$expected = '<div class="kittens" data-toggle="modal" data-lang="es"></div><div id="puppies" data-value="foo" data-lang="en"></div><div></div>';
$this->assertEquals($expected, $result);
// Test default creation of empty attribute object and using its method.
$result = $twig->render("<div{{ create_attribute().addClass('meow') }}></div>");
$expected = '<div class="meow"></div>';
$this->assertEquals($expected, $result);
}
}
class TwigExtensionTestString {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment