如何通过JavaScript传递参数实例化Pug mixin?
核心前提
Pug 是编译时运行的模板引擎,你的代码在打包/服务端渲染阶段就已经被编译为纯HTML,浏览器运行环境中不存在mixin species这个可调用的实体,所以无法直接在onClick事件中调用Pug语法的mixin,可通过以下两种方案实现需求:
方案1:预编译mixin为前端静态模板(推荐,性能更高)
适合mixin结构简单、对页面加载性能有要求的场景:
- 先把你的mixin对应的HTML结构抽成前端可复用的模板片段,用原生
template标签存储。比如你原mixin的定义如下:
mixin species(id) .species-item(data-id=id) h3 物种 #{id} p 这是第#{id}个物种卡片
你可以在Pug代码中提前写好隐藏的模板结构:
template#speciesTemplate .species-item h3 物种 <span class="id-slot"></span> p 这是第<span class="id-slot"></span>个物种卡片 button#addSpeciesBtn 添加物种 #speciesContainer
- 编写前端JS逻辑,维护自增id计数器,点击按钮时克隆模板、替换id占位符后插入容器:
// 初始化id计数器 let speciesId = 1 const addBtn = document.querySelector('#addSpeciesBtn') const container = document.querySelector('#speciesContainer') const template = document.querySelector('#speciesTemplate') addBtn.addEventListener('click', () => { // 克隆模板内容 const newItem = template.content.cloneNode(true) // 替换所有id占位符 newItem.querySelectorAll('.id-slot').forEach(el => el.textContent = speciesId) // 给卡片绑定data-id属性 newItem.querySelector('.species-item').dataset.id = speciesId // 插入容器 container.appendChild(newItem) // id自增 speciesId++ })
方案2:引入客户端版Pug在前端直接编译mixin
适合mixin逻辑复杂、不想重复维护模板结构的场景:
- 先将客户端版本的Pug运行库下载到本地后引入到项目中
- 将你的mixin代码存为字符串,提前编译为可调用的渲染函数:
// 你的mixin代码字符串 const speciesMixin = ` mixin species(id) .species-item(data-id=id) h3 物种 #{id} p 这是第#{id}个物种卡片 ` // 封装渲染方法 const renderSpeciesItem = (id) => { return pug.render(`${speciesMixin}\n+species(${id})`) } // 点击事件逻辑 let speciesId = 1 const addBtn = document.querySelector('#addSpeciesBtn') const container = document.querySelector('#speciesContainer') addBtn.addEventListener('click', () => { const itemHtml = renderSpeciesItem(speciesId) container.insertAdjacentHTML('beforeend', itemHtml) speciesId++ })
该方案需要额外加载Pug编译库,页面加载和渲染性能低于方案1。
内容的提问来源于stack exchange,提问作者era
相关产品推荐
相关产品推荐

