28

Using knockout.js, how do I include a carriage return in the text that is bound to the text attribute of a paragraph <p> element.

In my ViewModel I generated a string of text that is bound to the <p> in the View. I want to include carriage returns in the string which the browser displays with the line breaks.

Including <br /> or Environment.NewLine in the string does not seem to work.

nemesv
  • 138,284
  • 16
  • 416
  • 359
Martin
  • 1,001
  • 3
  • 13
  • 17

2 Answers2

62

You need to set a css property in your element. white-space: pre-wrap

<p style="white-space: pre-wrap">First name: <strong data-bind="text: firstName">todo</strong></p>
<p>Last name: <strong>todo</strong></p>

function AppViewModel() {
    this.firstName = "Bert" + " \n " + "Test";
    this.lastName = "Bertington";
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());

Then the code works. with \n

bdukes
  • 152,002
  • 23
  • 148
  • 175
DevZer0
  • 13,433
  • 7
  • 27
  • 51
  • 5
    I think this solution is much better because there is no html characters specific to html in the javascript. – Samuel Nov 03 '14 at 15:28
  • Definitely a better solution, especially where the data is user edited data, the HTML solution would require the use of a WYSIWYG editor which is completely unnecessary – squarelogic.hayden Jul 22 '15 at 10:27
18

You can use the html binding.

JS:

function AppViewModel() {
    this.firstName = "Bert<br\>Test";
    this.lastName = "Bertington";
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());

View :

<p>First name: <strong data-bind="html: firstName">todo</strong></p>
<p>Last name: <strong>todo</strong></p>

See fiddle

Damien
  • 8,889
  • 3
  • 32
  • 40