TWIG, how to get the first word of a string?

I have a string and I want

  • isolate the first word for styling with style1 and
  • display the rest of the line in 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.

+6
source share
2 answers

I found it split () and () TWIG.

 {% 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 for giving me an idea idea.

+12
source

I believe that you can achieve this using the split command in Twig. To separate, you need to define a separator between two words. Suppose your words are separated by a space. Then you can get the first and second words like this.

 {{ "Monday Tuesday" | split(' ')[0] }} 

Returns Monday

 {{ "Monday Tuesday" | split(' ')[1] }} 

Returns "Tuesday"

More on split: - http://twig.sensiolabs.org/doc/filters/split.html

Hope this helps, Hooray!

+11
source

Source: https://habr.com/ru/post/970994/


All Articles