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

Hugo模板中Scratch与变量插值差异及条件判断问题

在Hugo模板if条件中正确读取Scratch值的方法

核心问题出在Hugo模板的上下文变化——当你用range遍历.Site.Data.carousels时,当前的.会指向循环中的每个元素,这时候直接调用.Scratch访问的是当前元素的Scratch(而元素本身并没有Scratch属性),而非你在短码中设置的那个Scratch实例。

解决方法有两种:

方法1:用$引用上层上下文的Scratch

在range内部,$会保留对短码原始上下文的引用,所以可以通过$.Scratch.Get来读取你之前存储的值:

{{ $dataSource1 := "two" }}
{{ .Scratch.Set "dataSource2" "two" }}

{{ range $key, $value := .Site.Data.carousels }}
  {{ if eq $key $dataSource1 }}
    <p>Key is indeed two!</p>
  {{ end }}
  <!-- 修改这里,用$.Scratch.Get代替.Scratch.Get -->
  {{ if eq $key ($.Scratch.Get "dataSource2") }}
    <p>Key is indeed two!</p>
  {{ end }}
{{ end }}

方法2:提前将Scratch值存入变量

在range循环开始前,先把Scratch中的值取出来存到一个变量里,后续直接用变量判断即可,完全避开上下文变化的问题:

{{ $dataSource1 := "two" }}
{{ .Scratch.Set "dataSource2" "two" }}
<!-- 提前取出Scratch值到变量 -->
{{ $dataSource2 := .Scratch.Get "dataSource2" }}

{{ range $key, $value := .Site.Data.carousels }}
  {{ if eq $key $dataSource1 }}
    <p>Key is indeed two!</p>
  {{ end }}
  {{ if eq $key $dataSource2 }}
    <p>Key is indeed two!</p>
  {{ end }}
{{ end }}

这两种方法都能解决你遇到的判断失效问题,第二种方法更直观,也不容易因为上下文变化出问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 08:49:58