You are here

public function TwigExtensionTest::testCreateAttribute in Drupal 9

Same name and namespace in other branches
  1. 8 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()

Tests creating attributes within a Twig template.

@covers ::createAttribute

File

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

Class

TwigExtensionTest
Tests the twig extension.

Namespace

Drupal\Tests\Core\Template

Code

public function testCreateAttribute() {
  $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',
    ],
    [],
  ];
  $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 ArrayLoader([
    $name => "<div{{ create_attribute().addClass('meow') }}></div>",
  ]);
  $twig
    ->setLoader($loader);
  $result = $twig
    ->render($name);
  $expected = '<div class="meow"></div>';
  $this
    ->assertEquals($expected, $result);
}