'Dynamically generate / omit HTML attribute in Twig

I want to generate a div with a specific HTML attribute present or absent in it, in function of if a variable my_var has been defined or not. If it has been defined, its value should be used as the according attribute.

my_var is either not defined or equal to a value consisting of several words separated by a space (software needs these, I know it's not usual...).

I've tried the following:

<div class="container" {{ my_var ? "data-my-var='" ~ {{ my_var }} ~ "'" : ""}}>
</div>

But this escapes the quotes I use and yields sth like this in my output, with my_var = hello there how are you:

<div class="container" data-my-var=&quot;hello there how are you&quot;>
</div>

This does not change when I escape the quotes using

"data-my-var=\"" ~ {{ my_var }} ~ "\""

instead of what's written above.

I've also tried to simply omit the quotes, so do sth like:

"data-my-var=" ~ {{ my_var }}

which resulted in the attribute data-my-var being output with no quotes whatsoever; hence only recognizing the first word of the value of my_var.

So how can I reach what I want?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source