node.js - EJS - 将新行转换为 <br/> 并保持内容编码

标签 node.js ejs

这类似于 Jade - convert new lines to <br/> and keep the content encoded

那么有没有简单的方法可以在 ejs 中执行相同的操作:

<%- escape(foo).replace(/\n/g, '<br/>') %>

这可以通过从 ejs 中提取转义方法并分配给 res.locals 来实现,但如果可能的话,我正在寻找更优雅的东西

最佳答案

当我必须在页面中显示 git 提交消息时,我遇到了类似的问题。我查看了 GitLab 如何格式化提交消息,发现它们使用 white-space: pre-wraphttps://developer.mozilla.org/en-US/docs/Web/CSS/white-space

所以在我的 .ejs 文件中我使用:

<div style="white-space: pre-wrap"><%= commit.body %></div>

关于node.js - EJS - 将新行转换为 <br/> 并保持内容编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350529/

相关文章:

node.js - 穆尔特 |不断收到 "The "路径“参数必须是字符串类型。收到的类型为数字”

node.js - AngularJS 和 NodeJS 中的 View 模板引擎在概念上有什么区别?

javascript - 有没有办法访问 DOM 服务器端?

Node.js morgan 记录器输出未出现在控制台上

javascript - 在 Pell Editor 中粘贴 html 内容并使用 Striptags nodejs 包进行格式化

javascript - node.js 中的 socket.setTimeout()

html - 带空格的ejs字符串变量无法正确显示

javascript - 使用 Node.JS 下载 Torrent

node.js - 使用 ejs 和 express 时出现引用错误

node.js - NodeJS Express - 渲染页面自动更新