TWIG how to get the first word of a string? - symfony

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 }}

Related

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="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 %}

How to extract the first letter of a word with TWIG?

In a Drupal 8 views, I have a field with a token.
How to extract the first letter of a word with TWIG ?
I just want to display the first letter of the token in this field.
enter image description here
I tested the following code, but it doesn't work :
{{ '{{ name }}'|first }}
Try out :
{{ name|first }}
or
{{ name|slice(0, 1) }}
Twig: How to get the first character in a string
for a text field you can use :
content.field_lastname.0['#context'].value[0:1]

Remove the '\' from a string in twig

I have this text :
Ch d\`Arnb
Now I want to remove all \ from string if exist. I try a lot of solutions, one of this : {{ item|replace({'\/': ''}) }}. But without success. What can I try next?
There is an error in the replace parameter. You are presently trying to remove the / char. Try this:
{% set item = 'Foo\Bar' %}
{{ item|replace({'\\': ''}) }}
Output: FooBar

Keep leading 0 in Twig

In my database, I have a field containing the following data : 000010 (the type is integer)
In my twig tpl, I want to display it, then I do : {{ spending.documentName }}
But the browser displays "10". As if Twig was automaticcaly performing a trim on my data.
I tried {{ spending.documentName|raw }} but it doesn't work. I dont find anything on Google about how to keep leading 0 with Twig.
Does anyone know how to proceed ?
I think you must force the format (as your type is integer).
You can use the format filter :
{{ "%06d"|format(spending.documentName) }}
Or better create a twig extension (http://symfony.com/doc/current/cookbook/templating/twig_extension.html):
public function strpad($number, $pad_length, $pad_string) {
return str_pad($number, $pad_length, $pad_string, STR_PAD_LEFT);
}
It's clearer in your template :
{{ spending.documentName | strpad(6,'0') }}
You need to use the format filter.
Since placeholders follows the sprintf() notation, you should be able to convert sprintf('%06d', $integer); in PHP to {{ '%06d'|format($integer) }} in Twig.
Kinda late here, but ran into the same.
With twig 3.x you can use:
{{your.number | format_number({min_integer_digit:'2'})}}

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