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

如何在Pug mixin中用传入的id参数替换input属性内的固定值1

实现方法

在Pug中可以通过动态属性拼接的方式替换固定数值,只需要把原有静态属性值里的1替换为mixin接收的id参数即可,两种写法都可以正常运行:

  1. ES6模板字符串写法(适配新版Pug环境)
mixin workExperience(id, position, company, dateFrom, dateTo)
  section#work
    section.work-item
      input.toggle-item(id=`work-item-${id}` type='checkbox' checked='checked')
      label(for=`work-item-${id}`)
      header
        .position= position
        .company= company
        .date
          span.startDate= dateFrom
          span.endDate= dateTo
  1. 普通字符串拼接写法(兼容低版本Pug环境)
mixin workExperience(id, position, company, dateFrom, dateTo)
  section#work
    section.work-item
      input.toggle-item(id='work-item-' + id type='checkbox' checked='checked')
      label(for='work-item-' + id)
      header
        .position= position
        .company= company
        .date
          span.startDate= dateFrom
          span.endDate= dateTo

调用示例

调用mixin时传入对应id即可生效,比如:
+workExperience('2', '前端开发工程师', '某科技有限公司', '2021-01', '至今')
上述调用生成的HTML中,input的id为work-item-2,label的for属性也同步为work-item-2,表单控件关联关系正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 02:15:10