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. 10 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 336

Class

TwigExtensionTest
Tests the twig extension.

Namespace

Drupal\Tests\Core\Template

Code

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