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!

0

5 Answers 5

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.

1
  • 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
    Commented Oct 6, 2014 at 20:18
11

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

{% set address = contact.address|nl2br|raw %}
2
  • 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... Commented Sep 30, 2014 at 13:56
  • found a solution?
    – william
    Commented Aug 30, 2016 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 }}

1

Add raw before nl2br

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

This will work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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