Mustache.js只允许换行,转义其他HTML [英] Mustache.js allow only line breaks, escape other HTML

查看:159
本文介绍了Mustache.js只允许换行,转义其他HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建用户输入的注释,并在用户点击提交后使用Mustache.js呈现它们。我意识到我可以用< br /> 替换用户输入换行符( \ n )以呈现为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 />');

我意识到我可以通过使用三个括号使Mustache不能逃脱HTML

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

{{{myString}}}

但是,我想要转义所有用户HTML,因为Mustache通常会使用double大括号 {{...}} ,但允许换行符< br />

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.

推荐答案

选项1 - 使用预标记:

Option 1 - Use a pre tag:

实际上,最好(或有效)包装文本在< pre>< / pre> 标记中,这将保留文本中的空白区域。

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

并启用自动换行

< a href =https://stackoverflow.com/questions/248011/how-do-i-wrap-text-in-a-pre-tag>如何在预标签中包装文字?
- http://jsfiddle.net/X5ZY7/


选项2 - 将字符串拆分为行,并使用胡须e each:

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

comment = userComment.split("\n")


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


选项3 - 使用标签之前的tags-as-html-entities>最喜欢的方法

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


{{{comment}}}

这篇关于Mustache.js只允许换行,转义其他HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆