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!

30

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.

  • 1
    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 6 '14 at 20:18
10

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

{% set address = contact.address|nl2br|raw %}
  • 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>

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 }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.