Home > Software design >  Dynamically generate / omit HTML attribute in Twig
Dynamically generate / omit HTML attribute in Twig

Time:02-11

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  {{ 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  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?

CodePudding user response:

Variables and concatenations with variables are not marked as safe by default. You will need to apply the filter raw to mark the output as safe. Also you can omit the second part if you just return an empty string

<div {{ my_var ? (' data-my-var="' ~my_var ~ '"')|raw }}>
</div>

demo


Another method, as commented by @Bossman is to use an {% if ... %}{% endif %}

  • Related