Convert new line to line break in twig
In Twig, you can use the nl2br
filter to convert new lines (\n
) to line breaks (<br>
) in your template.
Here's an example:
{{ "Hello\nWorld" | nl2br }}
This would output:
Hello<br>World
The nl2br
filter replaces each newline character (\n
) with a line break (<br>
).
You can also use this filter on a variable that contains a string with new lines:
{% set text = "Hello\nWorld" %}
{{ text | nl2br }}
This would output the same result as above.
Note that the nl2br
filter is only available in Twig 1.12 and later versions. In earlier versions of Twig, you can use the replace
filter instead:
{{ "Hello\nWorld" | replace("\n", "<br>") }}