How to handle new line in handlebar.js
Asked Answered
U

3

6

I am using HandleBar.js in my rails jquery mobile application.

I have a json returned value data= "hi\n\n\n\n\nb\n\n\n\nhow r u"

which when used in .hbs file as {{data}} showing me as hi how r u and not as with the actual new line inserted

Please suggest me.

Pre tag helps me

Undersexed answered 25/6, 2012 at 14:8 Comment(1)
Maybe this can help #12331577Finlay
T
4

Handlebars doesn't mess with newlines in your data unless you have registered a helper which is doing something with them. A good way of dealing with newlines in HTML without converting them to br tags would be to use the CSS property white-space while rendering the handlebars template in HTML. You can set its value to pre-line.

Read the related documentation on MDN

Torin answered 5/1, 2015 at 4:22 Comment(0)
R
1

Look at the source of the generated file - your newline characters are probably there, HTML simply does not render newline characters as new lines.

You can insert a linebreak with <br />

However, it looks like you're trying to format the position of your lines using newline characters, which technically should be done by wrapping your lines in <p> or <div> tags and styling with CSS.

Rosenzweig answered 25/6, 2012 at 21:19 Comment(1)
No in the source also it doesnt have any new lines. But its saved with \n in table..Undersexed
R
1

Simply use the CSS property white-space and set the value as pre-line

For a example:

<p style="white-space: pre-line">
  {{text}}
</p>
Reinhard answered 12/7, 2022 at 8:58 Comment(1)
This was already suggested by the accepted answer from seven years ago. Please don't repeat answers.Willner

© 2022 - 2025 — McMap. All rights reserved.