Skip to content

[TwigComponent] A HtmlTag meta-component to easily renders dynamic HTML tag / attributes #940

Closed as not planned
@Kocal

Description

@Kocal

Hi!

Sometimes, inside a Twig template, you need to render HTML with a dynamic tag or attributes, depending if variables/props are presents, depending of their values, etc...

Given the following template:

{% set tag = href ? 'a' : 'p' %}

<{{ tag }}
    {% if href %} href="{{ href }}"{% endif %}
    {% if title %} title="title"{% endif %}
    {% if newTab %} target="_blank"{% endif %}
>
    ...
</{{ tag }}>

We can see that it is not easy to render a dynamic tag (you must think about the closing tag too), and you can't re-use attributes nor use a new ComponentAttributes instance (because you are not inside a Twig Component) to easily render tags.

Currently you need to do it yourself and it can leads to inconsistency / bad readability.

With a new meta-component (which has no logic but to renders HTML), we can imagine passing a tag and HTML attributes as an object (think as a simplified h function):

{% component HtmlTag with {
    _tag: href ? 'a' : 'p',
    href,
    title,
    ...(newTab ? { target: '_blank' } : {})
} %}
    ...
{% endcomponent %}

(The _ prefix in _tag is here to prevent a potential conflict with a tag HTML attribute, but maybe there is a better solution?)

The template associated to this components would looks like this:

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

WDYT?
Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions