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

javascript - Mustache.js allow only line breaks, escape other HTML - Stack Overflow

programmeradmin1浏览0评论

I am creating comments from user input and rendering them using Mustache.js after a user clicks 'submit'. I realize I can replace user input line breaks (\n) with <br/> to render as HTML breaks, such as

myString.replace(/\n/g, '<br />');

and I realize I can make Mustache not escape HTML by using triple brackets

{{{myString}}}

However, I would like to escape all user HTML as Mustache would typically do with double braces {{ ... }}, with the exception of allowing line breaks with <br/>

What is the best way to do this? I can replace the line breaks after it has been rendered, but that seems like a very inefficient solution, and I'm thinking there has to be a better way.

I am creating comments from user input and rendering them using Mustache.js after a user clicks 'submit'. I realize I can replace user input line breaks (\n) with <br/> to render as HTML breaks, such as

myString.replace(/\n/g, '<br />');

and I realize I can make Mustache not escape HTML by using triple brackets

{{{myString}}}

However, I would like to escape all user HTML as Mustache would typically do with double braces {{ ... }}, with the exception of allowing line breaks with <br/>

What is the best way to do this? I can replace the line breaks after it has been rendered, but that seems like a very inefficient solution, and I'm thinking there has to be a better way.

Share Improve this question asked Jan 21, 2014 at 7:19 RyanRyan 18.1k24 gold badges64 silver badges90 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

Option 1 - Use a pre tag:

It's actually best (or efficient) that you wrap text in a <pre></pre> tag, which will preserve the white space in the text.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre

And enable word-wrap

How do I wrap text in a pre tag? - http://jsfiddle.net/X5ZY7/


Option 2 - Split your string into lines, and use a mustache each:

comment = userComment.split("\n")


{{#comment}}
    {{comment}}<br/>
{{/comment}}


Option 3 - Manually escape your string using your favorite method before injecting the
tags:

var div = document.createElement("div")
div.textContent = comment
comment = div.innerHTML.replace(/\n/g, "<br/>")


{{{comment}}}

If you're looking to add line breaks to a textarea you need to replace \n with &#13;&#10;

发布评论

评论列表(0)

  1. 暂无评论