Dynamically generate / omit HTML attribute in Twig - symfony

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="hello there how are you">
</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?

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 class="container"{{ my_var ? (' data-my-var="' ~my_var ~ '"')|raw }}>
</div>
demo
Another method, as commented by #Bossman is to use an {% if ... %}{% endif %}

Related

translation strings in twig inside an object

I'm trying to put translation strings inside an object within Twig. So far I haven't got it right and can't figure out how to properly do it. I didn't think this would work, but it was my best effort so far.
{% set options = {
0 : {{ 'user.first_name'|trans }},
1 : {{ 'user.surname'|trans }},
2 : {{ 'user.initials'|trans }}
} %}
I get the error:
A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{".
Any one any ideas? Thanks in advance.
The syntax {{ ... }} is used to output content. You don't need to interpolate the variable in order to add it to the object
{% set options = {
0 : user.first_name|trans,
1 : user.surname|trans,
2 : user.initials|trans,
} %}
Some extra notes. As you are using numeric indices you could use the following snippet
{% set options = [
user.first_name|trans,
user.surname|trans,
user.initials|trans,
] %}
demo

Can I pass a dynamic value from craft CMS to another template as well as a string value?

Can I pass a dynamic value from craft CMS using twig to another template as well as a string value?
Using the following gives me a syntax error
"Twig_Error_Syntax: A hash key must be followed by a colon (:).
Unexpected token "punctuation" of value "," ("punctuation" expected with value ":") "
{% set myEntry= craft.entries.slug('myEntry').first %}
{% embed '_layouts/_hero' with {
'extraClasses': "{{ myEntry.featuredBgPosition }} hero--medium",
'heroImage': myEntry.featuredImage.first
} %}
Other answers say to not use curly braces but this doesn't work either
'extraClasses': myEntry.featuredBgPosition "hero--medium",
and when using it within the quotations I get the string myEntry.featuredBgPosition as a class
'extraClasses': myEntry.featuredBgPosition "hero--medium",
The answers that suggest removing the curly braces are correct, but you need to concatentate strings with variables.
{% set myEntry= craft.entries.slug('myEntry').first %}
{% embed '_layouts/_hero' with {
'extraClasses': myEntry.featuredBgPosition ~ " hero--medium",
'heroImage': myEntry.featuredImage.first
} %}

Set html id attribute dynamically in Twig

I'm trying to set the id of an element using a variable in a Twig template (not a form) without using JavaScript.
The template code looks like this:
{% set show_id = 'show' ~ entity.id %}
{{ dump(show_id) }}
<div class="event_option" id="show_id">
show
</div>
The show_id variable is dump'ed correctly, but when I try to use it as the html id in id="show_id", the id that gets assigned to the div is the string "show_id", and not the actual value of show_id. I get the same result when no parenthesis are used when assigning the html id, as in id=show_id. How can I access the Twig variable when assigning the html id attribute?
You should enclose with double bracket to tell Twig to print the value of variable
<div class="event_option" id="{{show_id}}">
show
</div>

TWIG how to get the first word of a string?

I've got a string and I want to
isolate the first word for styling with style1 and
display the rest of the string with style2 without the first word.
Something like that :
<span class="style1">{{ string|firstword() }}</span>
<span class="style2">{{ string|restofstring() }}</span>
Is it possible ? Thank you in advance.
I believe you can achieve this by using the split command in Twig. To split you need to identify the separator between two words. Assume your words are separated using a space. Then you can get the first and second words like this.
{{ "Monday Tuesday" | split(' ')[0] }}
Will return the "Monday"
{{ "Monday Tuesday" | split(' ')[1] }}
Will return the "Tuesday"
More about split :- http://twig.sensiolabs.org/doc/filters/split.html
Hope this helps,
Cheers!
I found it ! With split() and attribute() TWIG functions.
{% set array = article.titre|split(' ', 2) %}
<span class="style1">{{ attribute(array, 0) }}</span><!-- First word -->
<span class="style2">{{ attribute(array, 1) }}</span><!-- Rest of string -->
Thanks to Anjana Silva who give me the begginning of the idea.
As an alternative to the array syntax, you might find the first filter to be more idiomatic:
{{ "Hello Twig"|split(' ')|first }}

Symfony2 : Auto htmlentities using Twig

I'm displaying some variable retrieved in my database using Twig :
<p>{{ my_variable }}</p>
The thing is this variable may contain html tags, such as "<br />".
Twig seems to automatically call some htmlentities-like function when displaying variables.
Is there any way to disable it so that when I display a variable containing "Hello<br />world !" I get :
Hello
world !
rather than :
Hello<br />world !
Thanks
Use {{ my_variable|raw }} to prevent my_variable from being automatically escaped.
See Twig documentation: http://twig.sensiolabs.org/doc/filters/raw.html
Try using this
{% autoescape false %}{{ my_variable}}{% endautoescape %}
even better: {{ '<br />|raw('html') }} to avoid unescaping other sensible stuff.
If you just want to use linebreaks in the text stored in your database but don't care to use html , you can also use the nl2br filter as in {{ var|nl2br }}. Allows you to use string linebreak character \n in your text. Filter converts it to <br/>

Resources