gpt4 book ai didi

javascript - 在 Handlebars 模板中处理多行字符串

转载 作者:数据小太阳 更新时间:2023-10-29 05:46:52 24 4
gpt4 key购买 nike

从我的服务器返回的 JSON 响应包含一个长字符串(消息正文或多行注释)。

典型的 message.body 可能看起来像这样:

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

现在使用 Handlebars ,我是这样嵌入的

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

但是,这在 html 中呈现为:

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

Sincerely,

Austin"</p>

我怎样才能让它在它自己的 html 段落 [p] 标记中呈现每一行?在 rails 中,我会用这样的东西(在 haml 中)来做到这一点

- note.body.each_line do |x|
%p= x

最佳答案

您可以添加一个 Handlebars“Helper”

http://handlebarsjs.com/expressions.html(向下滚动到助手)

例如

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);
});

然后在你的模板调用中

{{paragraphSplit body}}

关于javascript - 在 Handlebars 模板中处理多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15982976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com