【发布时间】:2015-10-26 16:14:16
【问题描述】:
这类似于Jade - convert new lines to <br/> and keep the content encoded
那么有没有简单的方法在 ejs 中做同样的事情:
<%- escape(foo).replace(/\n/g, '<br/>') %>
这可以通过从 ejs 中提取转义方法并分配给 res.locals 来实现,但如果可能的话,我正在寻找更优雅的东西
【问题讨论】:
这类似于Jade - convert new lines to <br/> and keep the content encoded
那么有没有简单的方法在 ejs 中做同样的事情:
<%- escape(foo).replace(/\n/g, '<br/>') %>
这可以通过从 ejs 中提取转义方法并分配给 res.locals 来实现,但如果可能的话,我正在寻找更优雅的东西
【问题讨论】:
当我不得不在我的页面中显示 git commit 消息时,我遇到了类似的问题。我查看了 GitLab 如何格式化提交消息,发现它们使用 white-space: pre-wrap。 https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
所以在我的 .ejs 文件中我使用:
<div style="white-space: pre-wrap"><%= commit.body %></div>
【讨论】:
您可以使用<%= %> 转义html,以及您已有的替换功能(假设foo 是一个字符串)。
<%= foo.replace(/\r\n/g, '<br/>')) %>
【讨论】:
<%= 使用编码尖括号是正确的。您是否尝试对所有字符进行编码 然后 将 \r\n 替换为