Skip to content

[TwigComponent] attributes.has() method #1571

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 5, 2024

Conversation

barbieswimcrew
Copy link
Contributor

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.

{# templates/components/Button.html.twig #}
{% set element = attributes.has('href') ? 'a' : 'button' %}

<{{ element }} {{ attributes }}>
    {% block content %}{% endblock %}
</{{ element }}>

@carsonbot carsonbot added the Status: Needs Review Needs to be reviewed label Mar 1, 2024
@smnandre
Copy link
Member

smnandre commented Mar 1, 2024

Could we implement ArrayAccess to simplify all this ?

@kbond
Copy link
Member

kbond commented Mar 2, 2024

Solid use case. Trying to think if there's any downsides to @smnandre's suggestion.

@barbieswimcrew
Copy link
Contributor Author

Solid use case. Trying to think if there's any downsides to @smnandre's suggestion.

Hmm... let's say we would implement ArrayAccess... would the add() and offsetSet() methods become one? And if so... what would someone expect when using offsetSet(), for example? That you can add any attribute from inside? And what happens then with the custom logic from the current add() method?

And remove() would therefore become offsetUnset(), wouldn't it?

@smnandre
Copy link
Member

smnandre commented Mar 2, 2024

I'd implement only offsetExists and offsetGet, and throw a runtime exception in the two others..

it would "just" be syntaxic sugar to ease usage in templates :)

@carsonbot carsonbot added Status: Reviewed Has been reviewed by a maintainer and removed Status: Needs Review Needs to be reviewed labels Mar 5, 2024
@weaverryan
Copy link
Member

Because ComponentAttributes is a bit complex and we've been working a lot with subtle additions to it lately, I think we should keep it simple and just add has(). Thanks @barbieswimcrew!

@weaverryan weaverryan merged commit 8af8b3d into symfony:2.x Mar 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Status: Reviewed Has been reviewed by a maintainer
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants