Handling multiline strings in a pen template

The JSON response returned from my server includes a long string (message body or multi-line note).

A typical message.body might look something like this:

"Hi!\r\n\r\nHow life? Everything is well with me\r\n\r\nSincerely,\r\n\r\nAustin\r\n" 

Now, using the steering wheels, I build in like

<p>{{body}}</p>

However, this applies to this in html:

<p>"Hi!
How life? Everything is well with me 

Sincerely, 

Austin"</p>

How can I make this render every single line in my own html [p] paragraph tag? In rails, I would do it with something like this (in haml)

- note.body.each_line do |x|
    %p= x
+5
source share
2 answers

You can add Handlebars' helper

http://handlebarsjs.com/expressions.html (scroll down to helpers)

eg.

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 at the invitation of your template

{{paragraphSplit body}}
+10

Handlebars . , - :

var lines = "...".split(/(?:\r\n)+/);

:

var html = tmpl({ body: lines });

:

{{#each body}}
    {{.}}
{{/each}}

: http://jsfiddle.net/ambiguous/Gbu5w/

+4

All Articles