19

I'm looking for a way to output line break from a text field.

I'm aware of the "Allow line breaks" option and I have set that to true. I've then entered text with multiple new lines. However, when this text gets output in the template, there are no line breaks.

I have tried using Twig's new line to br function, like this:

{% set address = contact.address|nl2br %}

but this creates <br /> tags in the text, not the markup - that is, you can actually see the <br /> in the browser and no actual line breaks are being created.

Am I doing something wrong here? Are there any alternative solutions?

Thanks!

bravokiloecho
  • 1,583
  • 4
  • 17
  • 22

5 Answers5

32

Expanding from Pascal Mollet's answer, this was the solution I came up with.

First setting the address variable with the |nl2br filter:

{% set address = contact.address|nl2br %}

Then, outputting that variable with the |raw filter:

{{address|raw}}

Using them both together at once like this (as Pascal suggested):

{% set address = contact.address|nl2br|raw %}

didn't work.

bravokiloecho
  • 1,583
  • 4
  • 17
  • 22
  • 2
    I was able to use @Pascal's suggestion successfully - though instead of setting the variable, I just printed out the code like so: {{ contact.address|nl2br|raw }} – Ray Oct 06 '14 at 20:18
11

You could also add the Twig raw filter, which should prevent the automated escaping.

{% set address = contact.address|nl2br|raw %}
nicael
  • 2,382
  • 7
  • 27
  • 48
Pascal Mollet
  • 406
  • 2
  • 10
  • 1
    Thanks for your answer, and this is what I ended up doing with a small difference because using |nl2br and |raw together didn't work. A bit strange though that the |nl2br filter would encode the <br />'s... – bravokiloecho Sep 30 '14 at 13:56
  • found a solution? – william Aug 30 '16 at 18:44
2

Just using |nl2br inside a <p> tag (or whatever you choose) worked for me.

<p>{{ contact.address|nl2br }}</p>

Adam Menczykowski
  • 1,390
  • 11
  • 22
2

I'm using Craft v3.1, I noticed that none of the answers worked for me.

I only got it to work by placing raw before nl2br.

This is what worked for me: {{ entry.customFieldName |raw|nl2br }}

mateostabio
  • 526
  • 4
  • 16
1

Add raw before nl2br

{% set address = contact.address|raw|nl2br %}

This will work.

Ash
  • 41
  • 2