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

Node.js应用中按指定顺序渲染多个Pug模板的实现方案

实现多Pug模板顺序渲染的两种方案

不需要硬写if判断检测当前页面,有更清晰易维护的实现方式:

方案1:拆分不同提交路由(更推荐)

给每个模板的提交按钮绑定不同的路由,逻辑完全拆分,不需要做额外的状态判断:

  • template1页面的表单提交地址设为/step1,对应路由渲染template2
// 初始加载默认渲染第一个模板
app.get('/', async (req, res) => {
  res.render('template1')
})
// 处理第一步提交,跳转到第二个模板
app.post('/step1', async function(req, res, next) {   
  res.render('template2')
})
  • template2页面的表单提交地址设为/step2,对应路由渲染template3
app.post('/step2', async function(req, res, next) {   
  res.render('template3')
})
  • 后续步骤以此类推即可,每个步骤的逻辑完全独立,后续修改、新增步骤都不会互相影响。

方案2:单路由+隐藏参数实现

如果你坚持要用同一个/路由处理所有提交,可以在每个Pug模板里加隐藏字段标识当前步骤:

  1. 在template1的表单内添加隐藏输入:
input(type="hidden" name="current_step" value="1")
  1. 在template2的表单内添加隐藏输入:
input(type="hidden" name="current_step" value="2")
  1. 路由内用映射表匹配要渲染的模板,不需要写多分支if判断:
app.post('/', async function(req, res, next) {
  const step = Number(req.body.current_step) || 1
  const templateMap = {
    1: 'template2',
    2: 'template3',
    3: 'template4'
    // 后续新增步骤直接在映射表里加配置即可
  }
  res.render(templateMap[step])
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:15:03