Description
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