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

使用html-express-js模板引擎时浏览器源码无换行问题求助

解决html-express-js输出无换行问题及替代模板引擎推荐

一、修复当前html-express-js的换行问题

html-express-js默认会移除模板中的多余空白和换行,导致Chrome源码视图里的HTML没有格式。你可以通过手动格式化输出HTML来解决,步骤如下:

  1. 安装HTML格式化工具html-beautify:
npm install html-beautify
  1. 修改你的app.js,将原引擎的输出包装一层格式化逻辑:
import express from 'express';
import { resolve } from 'path';
import htmlExpress, { staticIndexHandler } from '../src/index.js';
import htmlBeautify from 'html-beautify'; // 引入格式化工具

const __dirname = resolve();
const app = express();

// 包装原引擎,添加格式化步骤
app.engine('js', async (filePath, options, callback) => {
  const originalEngine = htmlExpress({ includesDir: 'includes' });
  originalEngine(filePath, options, (err, rawHtml) => {
    if (err) return callback(err);
    // 配置格式化规则
    const formattedHtml = htmlBeautify(rawHtml, {
      indent_size: 2,
      preserve_newlines: true,
      end_with_newline: true,
      indent_inner_html: true
    });
    callback(null, formattedHtml);
  });
});

app.set('view engine', 'js');
app.set('views', `${__dirname}/example/public`);

// 其余代码保持不变
app.use(express.static(`${__dirname}/example/public`));

app.get('/hello', async function (req, res) {
  res.render('hello', {
    name: 'world',
  });
});

app.use(
  staticIndexHandler({
    viewsDir: `${__dirname}/example/public`,
    notFoundView: 'not-found',
  })
);

export default app;

这样渲染后的HTML会被自动格式化,Chrome源码视图里就能看到正常的换行和缩进了。

二、推荐适合的替代模板引擎

如果你不想折腾现有引擎,这些模板引擎默认支持保留换行,且学习成本低:

  • EJS:语法最接近原生HTML,直接在HTML里嵌入JS逻辑,模板里的换行和缩进会直接保留到输出中,新手友好,文档完善。
  • Nunjucks:功能全面,支持模板继承、包含等特性,默认输出会保留格式,语法和HTML兼容,上手快。
  • Handlebars:逻辑极简的模板引擎,强制分离视图和业务逻辑,可配置输出格式化,适合团队协作场景。
  • Pug:采用缩进式语法,写起来简洁,输出的HTML自动格式化,适合喜欢简洁语法的开发者,但需要适应缩进规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:52:55