Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top