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

如何在Pug模板的script标签中使用Node.js传递的变量

解决方法

你需要将服务端传递的prods变量序列化为JSON字符串后,注入到客户端JavaScript的上下文里,Pug模板默认会对输出内容做转义,所以需要用!语法关闭转义。

具体操作步骤

  1. 先修正现有Pug模板中的几处错误:
    • 你的产品对象属性名为Types,不是Type
    • 循环时的变量名拼写错误procucts应为products
    • 遍历数组推荐用for...of而非for...in,后者遍历的是数组索引而非元素
  2. 在script标签中先注入服务端的prods变量
    修正后的完整Pug代码如下:

下拉框部分

select(name="type" onchange="change()")#type
    option(value="Null") "Type"
    for product in prods
        option(value=product.Types) #{product.Types}

select(name="brands")#brands
     option(value="Null") "Brand"

script部分

script.
    // 注入服务端传递的prods数组,这里的!是关键,用于关闭Pug的默认转义
    const prods = !{JSON.stringify(prods)};
    function change() {
        const type = document.getElementById("type").value;
        const brandSelect = document.getElementById("brands");
        // 先清空已有品牌选项,避免重复叠加
        brandSelect.innerHTML = '<option value="Null">Brand</option>';
        
        // 遍历产品数组匹配对应分类的品牌
        for (const item of prods) {
            if (item.Types === type) {
                const brandOption = new Option(item.Brand, item.Brand);
                brandSelect.add(brandOption, undefined);
            }
        }
    }

原理说明

JSON.stringify(prods)会将服务端的JS数组转为JSON字符串,!前缀告诉Pug不要转义输出的内容,最终渲染到页面上时会变成标准的JS数组字面量,客户端脚本就可以直接读取使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:24:00