The JSON response returned from my server includes a long string (a message body, or multi-line note).
A typical message.body might look something like this:
"Hi!\r\n\r\nHow's life? Everything is well with me\r\n\r\nSincerely,\r\n\r\nAustin\r\n"
Using handlebars now, I'm embedding like this
<p>{{body}}</p>
However, this renders into this in html:
<p>"Hi!
How's life? Everything is well with me
Sincerely,
Austin"</p>
How can I get this to render each individual line within its own html paragraph [p] tag? In rails, I would do this with something like this (in haml)
- note.body.each_line do |x|
%p= x
HTML. Example 2: If you use double/single quote to write multiline string then we use the newline character (\n). Use an extra backslash ( \ ) after every newline character (\n), this backslash tells the JavaScript engine that the string is not over yet.
Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.
A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string. Python's indentation rules for blocks do not apply to lines inside a multiline string.
You could add a Handlebars 'Helper'
http://handlebarsjs.com/expressions.html (scroll down to Helpers)
e.g.
Handlebars.registerHelper('paragraphSplit', function(plaintext) {
var i, output = '',
lines = plaintext.split(/\r\n|\r|\n/g);
for (i = 0; i < lines.length; i++) {
if(lines[i]) {
output += '<p>' + lines[i] + '</p>';
}
}
return new Handlebars.SafeString(output);
});
Then in your template call
{{paragraphSplit body}}
Handlebars doesn't like logic in the template. You usually process your data before your template sees it with something like this:
var lines = "...".split(/(?:\r\n)+/);
and then feed that array to the template:
var html = tmpl({ body: lines });
Your template in such cases would look like this:
{{#each body}}
{{.}}
{{/each}}
Demo: http://jsfiddle.net/ambiguous/Gbu5w/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With