Antoine Subit
Antoine Subit

Reputation: 9913

TWIG how to get the first word of a string?

I've got a string and I want to

Something like that :

<span class="style1">{{ string|firstword() }}</span>
<span class="style2">{{ string|restofstring() }}</span>

Is it possible ? Thank you in advance.

Upvotes: 12

Views: 14663

Answers (3)

domsson
domsson

Reputation: 4691

As an alternative to the array syntax, you might find the first filter to be more idiomatic:

{{ "Hello Twig"|split(' ')|first }}

Upvotes: 0

Antoine Subit
Antoine Subit

Reputation: 9913

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.

Upvotes: 23

Anjana Silva
Anjana Silva

Reputation: 9191

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!

Upvotes: 24

Related Questions