You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express.js中如何在Pug模板换行渲染消息及传递样式?

解决方案

一、实现消息换行渲染

HTML默认会将换行符\n视为空白字符,直接输出不会换行,以下两种方法可以解决:

方法1:替换换行符为HTML标签+非转义输出

在Express路由中,把消息里的\n替换成<br>标签:

res.render('product', {
  title: '',
  message: 'Hello.\n\nthere.'.replace(/\n/g, '<br>')
});

然后在Pug模板中使用!=输出消息(=会自动转义HTML标签,!=保留原始HTML结构):

if message
  .alert.alert-danger(role='alert' style='background-color:#f2dede')
    p(style='color: black')
      != message

方法2:用CSS样式保留换行

无需修改Express中的消息内容,给Pug的<p>标签添加white-space: pre-wrap样式,让浏览器识别换行符:

if message
  .alert.alert-danger(role='alert' style='background-color:#f2dede')
    p(style='color: black; white-space: pre-wrap;')
      = message

pre-wrap会保留换行符,同时自动换行避免横向滚动,比<pre>标签更适配页面布局。

二、通过Express传递CSS样式

可以直接通过渲染上下文传递CSS样式,两种常用实现方式:

方式1:传递样式对象

在Express路由中定义样式对象:

res.render('product', {
  title: '',
  message: 'Hello.\n\nthere.'.replace(/\n/g, '<br>'),
  textStyles: {
    color: '#000',
    fontWeight: 'bold',
    fontSize: '16px'
  }
});

在Pug模板中通过模板语法拼接样式:

if message
  .alert.alert-danger(role='alert' style='background-color:#f2dede')
    p(style=`color: ${textStyles.color}; font-weight: ${textStyles.fontWeight}; font-size: ${textStyles.fontSize};`)
      != message

方式2:传递完整样式字符串

如果样式较多,直接传递拼接好的字符串更便捷:

res.render('product', {
  title: '',
  message: 'Hello.\n\nthere.'.replace(/\n/g, '<br>'),
  textStyle: 'color: #000; font-weight: bold; font-size: 16px;'
});

在Pug模板中直接引用:

if message
  .alert.alert-danger(role='alert' style='background-color:#f2dede')
    p(style=textStyle)
      != message

内容的提问来源于stack exchange,提问作者jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:48:25