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
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
Share
Improve this question
asked Apr 13, 2013 at 0:47
Austin WangAustin Wang
9199 silver badges19 bronze badges
2 Answers
Reset to default 10You could add a Handlebars 'Helper'
http://handlebarsjs./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/ambiguous/Gbu5w/