iamamac
iamamac

Reputation: 10126

How to generate a line break in Django template

I want to give default value to a textarea. The code is something like this:

<textarea>{{userSetting.list | join:"NEWLINE"}}</textarea>

where userSetting.list is a string list, each item of whom is expected to show in one line.

textarea takes the content between the tags as the default value, preserving its line breaks and not interpreting any HTML tags (which means <br>,\n won't work).

I have found a solution: {{userSetting.list | join:" " | wordwrap:0}} (there is no whitespace in the list). But obviously it is NOT a good one. Any help would be appreciated.

Upvotes: 6

Views: 12198

Answers (4)

Matt
Matt

Reputation: 223

For some reason the accepted answer did not work for me, but this did:

<div>{{ list|join:'<br>' }}</div>

Docs reference for join: https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#join

Upvotes: 1

Chris Leah
Chris Leah

Reputation: 79

Try using {{userSetting.list | join:"&#10;"}} if
and \n won't work. Let me know how you get on...

:P

Upvotes: 0

iamamac
iamamac

Reputation: 10126

Since Chris didn't come and collect the credit, I have to answer my question myself. (But still thanks him for pointing to the right direction)

The HTML entity &#10; stands for a NEWLINE character, and won't be interpreted in Django template. So this will work:

<textarea>{{userSetting.list | join:"&#10;"}}</textarea>

Upvotes: 9

bradlis7
bradlis7

Reputation: 3489

A textarea in HTML does respect newlines. Does this not escape the \n:

<textarea>{{userSetting.list | join:"\n"}}</textarea>

I'm thinking that it should turn the \n into a newline character, so your source looks like this:

<textarea>Setting 1
Setting 2
Setting 3</textarea>

This would work if it did, but it may not convert \n correctly.

Upvotes: 0

Related Questions