Mustache.js only allow line breaks, exit other HTML code

I create comments with user input and render them using Mustache.js after the user clicks the submit button. I understand that I can replace input line breaks ( \n ) with <br/> to render as HTML breaks like

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

and I understand that I can make Mustache not avoid HTML using triple brackets

{{{myString}}}

However, I would like to avoid all custom HTML, as Mustache would usually do with double brackets {{ ... }} , except for resolving line breaks with <br/>

What is the best way to do this? I can replace line breaks after rendering it, but this seems like a very inefficient solution, and I think there should be a better way.

+7
javascript mustache
source share
2 answers

Option 1 Use the preliminary tag:

It’s best (or effective) to wrap the text with a <pre></pre> that preserves the space in the text.

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

And enable word-wrap

How to wrap text in pre tag? - http://jsfiddle.net/X5ZY7/


Option 2 Divide the line into lines and use a mustache each:

 comment = userComment.split("\n") {{#comment}} {{comment}}<br/> {{/comment}} 


Option 3 Manually delete your line using your favorite method before inserting tags:

 var div = document.createElement("div") div.textContent = comment comment = div.innerHTML.replace(/\n/g, "<br/>") {{{comment}}} 
+10
source share

If you want to add line breaks in the text box, you need to replace \ n with & # 13; & # 10;

+1
source share

All Articles