[Twig] Is there a way to clean up this dynamic string?

I'm trying to build a dynamic class string:
{% set classes = 'custom-image ' ~ alignment ?? '' ~ ' ' ~ decoration ?? '' %}

<div class="{{ classes|trim }}">
{% include "_components/image.twig" with { image: image.asset } %}
</div>
{% set classes = 'custom-image ' ~ alignment ?? '' ~ ' ' ~ decoration ?? '' %}

<div class="{{ classes|trim }}">
{% include "_components/image.twig" with { image: image.asset } %}
</div>
This works, but it's kind of messy. I'd also like to eventually be able to have 'alignment' be something like alignment-<alignment> rather than the value. So for example, if alignment = left, right now it just adds left to the class list because it's easiest. But I'd like it to add alignment-left to the class list instead. I know how I can do this but not without making it messy. And even this current iteration, it's not perfect because if alignment is null, then it'll add 2 spaces instead of just one.
9 Replies
ἔρως
ἔρως3mo ago
{% set classes = [
'custom-image',
alignment ?? '',
decoration ?? ''
]|filter|join(' ') %}
{% set classes = [
'custom-image',
alignment ?? '',
decoration ?? ''
]|filter|join(' ') %}
it it doesn't work without the arrow function, change to |filter(v => v) https://twig.symfony.com/doc/3.x/filters/join.html https://twig.symfony.com/doc/3.x/filters/filter.html ^ documentation for you
vince
vinceOP3mo ago
Thanks Epic! I don't know why I didn't think about something like that... I think I was thinking I want to build a string so I should use string methods lol... I was able to get it to work just using join, without filter:
{% set classes = [
'custom-image',
alignment ?? '',
decoration ?? ''
]|join(' ') %}
{% set classes = [
'custom-image',
alignment ?? '',
decoration ?? ''
]|join(' ') %}
ty!! 🙂
ἔρως
ἔρως3mo ago
that works too, but it will make double-spaces if you're picky about it, the filter is your friend and you're welcome
vince
vinceOP3mo ago
It's not making double spaces in my limited testing but I'll use it if I see it 👀
ἔρως
ἔρως3mo ago
if you set decoration but not alignment, it will put 2 spaces
vince
vinceOP3mo ago
Ohh I see now! I modified it to this:
{% set classes = [
'custom-image',
alignment ?? '',
decoration ?? ''
]|filter(v => v != '')|join(' ') %}
{% set classes = [
'custom-image',
alignment ?? '',
decoration ?? ''
]|filter(v => v != '')|join(' ') %}
ἔρως
ἔρως3mo ago
just v didn't work?
vince
vinceOP3mo ago
I'll make '' to null too Nah
ἔρως
ἔρως3mo ago
weird
Want results from more Discord servers?
Add your server