Skip to content

Commit 8af8b3d

Browse files
committed
feature #1571 [TwigComponent] attributes.has() method (barbieswimcrew)
This PR was squashed before being merged into the 2.x branch. Discussion ---------- [TwigComponent] attributes.has() method | Q | A | ------------- | --- | Bug fix? |no | New feature? | yes | Issues | - | License | MIT Provide a `ComponentAttributes::has()` function to be able to check via `{{ attributes.has('foo') }}` whether the attribute has been passed. I would like to show the use case in the following example. Using `attributes.has('href')`, I check whether the TwigComponent has set an 'href' attribute when it is called. If so, an `<a>` tag should be rendered, otherwise a `<button>` tag. ```twig {# templates/components/Button.html.twig #} {% set element = attributes.has('href') ? 'a' : 'button' %} <{{ element }} {{ attributes }}> {% block content %}{% endblock %} </{{ element }}> ``` Commits ------- 3718a12 [TwigComponent] attributes.has() method
2 parents 5d2691d + 3718a12 commit 8af8b3d

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

src/TwigComponent/src/ComponentAttributes.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,11 @@ public function getIterator(): \Traversable
193193
return new \ArrayIterator($this->attributes);
194194
}
195195

196+
public function has(string $attribute): bool
197+
{
198+
return array_key_exists($attribute, $this->attributes);
199+
}
200+
196201
public function count(): int
197202
{
198203
return \count($this->attributes);

src/TwigComponent/tests/Unit/ComponentAttributesTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,4 +224,11 @@ public function testCannotRenderNonStringAttribute(): void
224224

225225
$attributes->render('attr1');
226226
}
227+
228+
public function testCanCheckIfAttributeExists(): void
229+
{
230+
$attributes = new ComponentAttributes(['foo' => 'bar']);
231+
232+
$this->assertTrue($attributes->has('foo'));
233+
}
227234
}

0 commit comments

Comments
 (0)