Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Multiline Strings in a Handlebars template

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
like image 299
Austin Wang Avatar asked Apr 13 '13 00:04

Austin Wang


People also ask

How do you write multi line strings in template literals?

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.

How do you use multiline strings?

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.

What is 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.


2 Answers

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}}
like image 181
Alasdair McLeay Avatar answered Sep 19 '22 10:09

Alasdair McLeay


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/

like image 23
mu is too short Avatar answered Sep 20 '22 10:09

mu is too short