最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Handling Multiline Strings in a Handlebars template - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 10

You 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/

发布评论

评论列表(0)

  1. 暂无评论