function TwigExtensionTest::testCreateAttribute

Same name in other branches
  1. 9 core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php \Drupal\Tests\Core\Template\TwigExtensionTest::testCreateAttribute()
  2. 8.9.x core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php \Drupal\Tests\Core\Template\TwigExtensionTest::testCreateAttribute()
  3. 11.x core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php \Drupal\Tests\Core\Template\TwigExtensionTest::testCreateAttribute()

Tests creating attributes within a Twig template.

@covers ::createAttribute

File

core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php, line 400

Class

TwigExtensionTest
Tests the twig extension.

Namespace

Drupal\Tests\Core\Template

Code

public function testCreateAttribute() : void {
    $name = '__string_template_test_1__';
    $loader = new ArrayLoader([
        $name => "{% for iteration in iterations %}<div{{ create_attribute(iteration) }}></div>{% endfor %}",
    ]);
    $twig = new Environment($loader);
    $twig->addExtension($this->systemUnderTest);
    $iterations = [
        [
            'class' => [
                'kittens',
            ],
            'data-toggle' => 'modal',
            'data-lang' => 'es',
        ],
        [
            'id' => 'puppies',
            'data-value' => 'foo',
            'data-lang' => 'en',
        ],
        [],
        new Attribute(),
    ];
    $result = $twig->render($name, [
        '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><div></div>';
    $this->assertEquals($expected, $result);
    // Test default creation of empty attribute object and using its method.
    $name = '__string_template_test_2__';
    $loader = new ArrayLoader([
        $name => "<div{{ create_attribute().addClass('meow') }}></div>",
    ]);
    $twig->setLoader($loader);
    $result = $twig->render($name);
    $expected = '<div class="meow"></div>';
    $this->assertEquals($expected, $result);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.