Symfony3 + Twig : Join array with <br/>
Asked Answered
S

4

7

I'm trying to display all elements inside an array and separate them with a line break, but I can't get it work.

Here is what I tried:

{{ user.roles | join('<br/>') }}
{{ user.roles | join('<br/>' | raw) }}
{{ user.roles | join('\n' | nl2br | raw) }}

Everytime I get something like:

ROLE_PARENT<br/>ROLE_ADMIN<br/>ROLE_MANAGER<br/>ROLE_USER

How can I tell twig to render <br/> as html ?

I could loop through the array but it's not the first time I tried to render html tag and I would like a definitive solution to this problem.

Sepulcher answered 5/5, 2017 at 14:41 Comment(0)
B
18

A slight modification to your third attempt should do the trick as well.

{{ user.roles | join('\n')| nl2br  }}
Babcock answered 5/5, 2017 at 14:50 Comment(1)
Is the | raw necessary? Isn't '\n' | raw evaluated first and then join() on the result of it?Stefanysteffane
S
3

I found the error, I'm not applying the filter at the right place, this works :

{{ user.roles | join('<br/>') | raw }}
Sepulcher answered 5/5, 2017 at 14:50 Comment(1)
Problem with this solution as opposed to the other one: if you have HTML tags in the original array's values, these will be rendered as well, due to applying raw. (Might be unimportant in this case, still thought it important to mention)Stefanysteffane
M
0

What about a loop ?

https://twig.sensiolabs.org/doc/2.x/tags/for.html

{%- for role in user.roles -%}
    {{- role -}}<br>
{%- endfor -%}

Note: You can manage whitespaces with -

https://twig.sensiolabs.org/doc/2.x/templates.html#whitespace-control

Mandrel answered 5/5, 2017 at 16:24 Comment(1)
Like I said in the post, I'm aware I could do a loop but this was not my question.Sepulcher
F
0

{{ user.roles | join("\n") | nl2br | raw }} This will work always

Docs https://twig.symfony.com/doc/3.x/filters/join.html

https://twig.symfony.com/doc/3.x/filters/nl2br.html

https://twig.symfony.com/doc/3.x/filters/raw.html

Foltz answered 2/12, 2022 at 16:19 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Nepos

© 2022 - 2024 — McMap. All rights reserved.