Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mustache.js allow only line breaks, escape other HTML

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.

like image 410
Ryan Avatar asked Jan 21 '14 07:01

Ryan


2 Answers

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}}}
like image 91
Matt Esch Avatar answered Oct 22 '22 00:10

Matt Esch


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

like image 26
blented Avatar answered Oct 22 '22 01:10

blented