我对 golang 知之甚少,对 go 模板了解更少。 然而,在我的职业生涯中,我用多种语言进行过编程。但我并没有采取结构化的方法来学习 Golang。因此,对于经验丰富的 golang 开发人员来说,这可能是显而易见的事情。 我在我的博客中使用 Hugo,并且喜欢扩展主题并创建我没有直接开箱即用的 UI 组件。
我最近正在使用 Hugo 的 carousel 短代码。 目前的短代码假设填充滑块轮播所需的所有数据都写入一个 yaml 配置中。如果您的网站上有多个轮播,并且每个轮播都需要显示一组不同的图像,则这是不切实际的。
我想让短代码采用一个参数 - 数据配置文件的名称,以便任何页面上的每个轮播都可以显示不同的图像集。
该设计意味着 Hugo 的
data
目录将具有以下结构:
data/
├── carousels/
│ ├── one.yaml
│ └── two.yaml
其中
one.yaml
和 two.yaml
包含各自轮播实例的配置。文件的内容将类似于以下格式。
images:
- image: /images/carousel-test/1.jpg
content_html: "1"
- image: /images/carousel-test/2.png
content_html: "2"
我使用以下代码创建了一个 test.md 用于渲染轮播。
{{< carousel items="2" height="500" unit="px" duration="7000" dataSource1="one" dataSource2="two">}}
现在为了创建一个轮播来演示
Scratch.Get dataSource2
和使用变量之间的差异 - $dataSource1
我决定通过首先读取数据源的参数来修改短代码定义 - 这将是每个轮播的配置文件。
{{ .Scratch.Set "height" (.Get "height") }}
{{ .Scratch.Set "unit" (.Get "unit") }}
{{ .Scratch.Set "ordinal" .Ordinal }}
{{ .Scratch.Set "items" (.Get "items") }}
{{ $dataSource1 := ((.Get "dataSource1") | default "one") }}
{{ .Scratch.Set "dataSource2" ((.Get "dataSource2") | default "two") }}
<div id="carousel{{ .Ordinal }}" class="carousel" duration="{{ .Get `duration` }}">
<p>Site.Data.carousels is {{ .Site.Data.carousels }}</p>
<p>dataSource1 is set to {{ $dataSource1 }}</p>
<p>dataSource2 is set to {{ .Scratch.Get "dataSource2"}}</p>
{{ range $key, $value := .Site.Data.carousels }}
<p> *** The <i>key</i> is <b>{{$key}}</b> while <i>value</i>: <b>{{$value}}</b> </p>
{{ if eq $key $dataSource1 }}
<p>Key is indeed one!</p>
{{end}}
{{ if eq $key (.Scratch.Get "dataSource2") }}
<p>Key is indeed two!</p>
{{end}}
{{end}}
<div class="prev">‹</div>
<div class="next">›</div>
</div>
我希望
Key is indeed two!
能够呈现在屏幕上。然而,它永远不会发生。在 if
的情况下从 Scratch 读取的正确方法是什么?
参考资料:
在您的 Go 模板中,问题可能在于如何将范围循环中的键与 dataSource2 的值进行比较。由于您从 .Scratch 访问值的方式,比较 eq $key (.Scratch.Get "dataSource2") 可能无法按预期工作。
{{ .Scratch.Set "height" (.Get "height") }}
{{ .Scratch.Set "unit" (.Get "unit") }}
{{ .Scratch.Set "ordinal" .Ordinal }}
{{ .Scratch.Set "items" (.Get "items") }}
{{ $dataSource1 := (.Get "dataSource1") | default "one" }}
{{ .Scratch.Set "dataSource2" ((.Get "dataSource2") | default "two") }}
<div id="carousel{{ .Ordinal }}" class="carousel" duration="{{ .Get `duration` }}">
<p>Site.Data.carousels is {{ .Site.Data.carousels }}</p>
<p>dataSource1 is set to {{ $dataSource1 }}</p>
<p>dataSource2 is set to {{ .Scratch.Get "dataSource2"}}</p>
{{ range $key, $value := .Site.Data.carousels }}
<p> *** The <i>key</i> is <b>{{$key}}</b> while <i>value</i>: <b>{{$value}}</b> </p>
{{ if eq $key $dataSource1 }}
<p>Key is indeed one!</p>
{{end}}
{{ if eq $key ($.Scratch.Get "dataSource2") }}
<p>Key is indeed two!</p>
{{end}}
{{ end }}
<div class="prev">‹</div>
<div class="next">›</div>
</div>
删除了 .Get“dataSource1”周围不必要的括号。 调整了 dataSource2 的 if 条件中的比较,以使用 $.Scratch.Get 而不是 .Scratch.Get。这应该确保从暂存空间中检索到正确的值。 通过这些更改,dataSource2 的 if 条件中的比较应该按预期工作,并且“Key 确实是两个!”如果键与 dataSource2 的值匹配,则应在屏幕上呈现。