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

如何让Pug公共partial的script标签移至父模板body闭合标签前?

如何将Pug公共Partial中的脚本移至父模板body末尾(多父模板场景)

问题场景

我有多个独立的Pug父模板(如index.pug、detail.pug),它们都引入了同一个my_partial.pug。当前渲染后,partial中的script标签会被插入到HTML内容中间,我希望将这类脚本统一移到父模板body标签闭合前。

尝试过block append scripts的方法,但由于该partial需要被多个无继承关系的父模板引入,无法使用extend,因此该方案无效。目前采用数组push的临时方案,寻求更优解决方法。

现有代码示例

父模板(index.pug):

body
  | I am the index.pug
  include my_partial
  | Some text

my_partial.pug:

| Inside partial
script(src="mypartial.js")

尝试过的block方案(无效):
父模板:

body
  | I am the index.pug
  include my_partial
  block scripts

partial:

| Inside partial
block appends scripts
  script(src="mypartial.js")

当前临时方案:
父模板:

| I am the index.pug
 - var bodyScripts = []
 include my_partial
 each scriptPath in bodyScripts
   script(src=scriptPath)

partial:

| Inside partial
- bodyScripts.push('mypartial.js')

更优解决方案

方案1:封装脚本收集逻辑为可复用Mixin

将脚本的初始化、添加、渲染逻辑封装成Mixin,让代码更整洁、可维护,避免重复编写数组操作代码:

  1. 创建script-collector.pug(复用的Mixin文件):
// 初始化脚本数组,避免未定义报错
mixin initScripts()
  - if (!locals.bodyScripts) locals.bodyScripts = []

// 添加脚本路径到数组
mixin addScript(src)
  - bodyScripts.push(src)

// 在body末尾渲染所有收集到的脚本
mixin renderScripts()
  each scriptPath in bodyScripts
    script(src=scriptPath)
  1. 修改父模板(如index.pug):
// 引入脚本收集Mixin
include script-collector.pug
// 初始化脚本数组
+initScripts()

body
  | I am the index.pug
  include my_partial
  | Some text
  // 在body末尾渲染脚本
  +renderScripts()
  1. 修改my_partial.pug:
// 引入脚本收集Mixin
include script-collector.pug
| Inside partial
// 添加当前partial的脚本路径
+addScript('mypartial.js')

方案2:利用框架全局变量(Node.js/Express环境)

如果是在Express等Node.js框架中使用Pug,可以通过app.locals定义全局的脚本收集数组(注意:若为多请求场景,需确保每个请求的数组独立,避免污染):

  1. 在Express初始化代码中添加:
app.use((req, res, next) => {
  res.locals.bodyScripts = [];
  next();
});
  1. 父模板简化为:
body
  | I am the index.pug
  include my_partial
  | Some text
  each scriptPath in bodyScripts
    script(src=scriptPath)
  1. partial保持临时方案的写法即可:
| Inside partial
- bodyScripts.push('mypartial.js')

原block方案无效原因

block appends依赖Pug的模板继承机制(extend),只有当partial是父模板的子模板(通过extend继承)时,partial中的block才能关联到父模板的对应block。而你的场景中,partial是被多个独立父模板直接include的,不存在继承关系,因此该方案无法生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:42:45