Reputation: 919
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
Upvotes: 5
Views: 5253
Reputation: 2642
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}}
Upvotes: 10
Reputation: 434805
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/
Upvotes: 5