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

Hugo如何仅在特定布局页面的页脚加载额外脚本?

方案1:使用模板块(最推荐)

借助Hugo模板继承的块能力,直接在全站通用JS加载完成的位置预留空块,特定布局按需实现该块即可,无需处理变量传递和缓存兼容问题。
修改base_of.html的尾部代码:

<!-- 仅生产环境缓存partial -->
    {{ if hugo.IsProduction }}
    {{ partialCached "script.html" . }}
    {{ partialCached "footer.html" . }}
    {{ else }}
    {{ partial "script.html" . }}
    {{ partial "footer.html" . }}
    {{ end }}
    <!-- 预留自定义脚本块,默认无内容 -->
    {{ block "custom-scripts" . }}{{ end }}
</body>
</html>

在需要加载额外JS的布局文件中新增块定义:

{{ define "main" }}
... 原有布局逻辑 ...
{{ end }}

{{ define "custom-scripts" }}
<!-- 此处脚本会在全站通用JS加载完成后执行 -->
<script src="/path/to/your/custom.js"></script>
{{ end }}

方案2:使用Page Scratch 跨作用域传值

如果需要将额外脚本的加载逻辑统一放到script.html中管理,可以使用Hugo页面对象绑定的Scratch存储跨作用域变量,不受模板块作用域限制。

  1. 在特定布局文件的开头设置标记:
{{ define "main" }}
{{ .Scratch.Set "load_custom_js" true }}
... 原有布局逻辑 ...
{{ end }}
  1. 在script.html的末尾添加判断逻辑:
... 原有通用JS加载逻辑 ...

{{ if .Scratch.Get "load_custom_js" }}
<script src="/path/to/your/custom.js"></script>
{{ end }}
  1. 如果使用partialCached加载script.html,需要添加变体参数避免缓存导致判断失效,修改base_of.html中的调用代码:
{{ partialCached "script.html" . (.Scratch.Get "load_custom_js") }}

方案3:直接判断布局类型(适用于固定布局场景)

如果是某类固定布局的所有页面都需要加载该额外JS,无需额外设置变量,直接在script.html末尾判断布局标识即可:

{{ if eq .Layout "你的特定布局名称" }}
<script src="/path/to/your/custom.js"></script>
{{ end }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:06:04