英文:
Pass str to .Site.GetPage in hugo
问题
在Hugo中,我想循环遍历一个字符串切片,然后使用当前字符串调用`.Site.GetPage`。
目前我收到以下错误:
在<.Site.GetPage>处执行模板失败: 无法在字符串类型中评估字段Site
我的代码如下:
{{ $array := slice "foo" "bar" "bam" }}
{{ range $array }}
{{ $imgStr := printf "%s" ".jpg" | printf "%s%s" . | printf "%s%s" "images/" | printf "%s" }}
{{ $img := resources.Get $imgStr }}
{{ $imgSrc := $img.RelPermalink }}
{{ with index .Site.GetPage . }}
<h1>{{ .Title }}</h1>
<img src="{{ $imgSrc }}">
<p>{{ .Content }}</p>
{{ end }}
{{ end }}
<details>
<summary>英文:</summary>
Within Hugo, I want to loop over a slice of strings and later use the current string to call `.Site.GetPage`.
Currently I receive the following error:
execute of template failed at <.Site.GetPage>: can’t evaluate field Site in type string
My code looks like this:
{{ $array := slice "foo" "bar" "bam" }}
{{ range $array }}
{{ $imgStr := printf "%s" ".jpg" | printf "%s%s" . | printf "%s%s" "images/" | printf "%s" }}
{{ $img := resources.Get $imgStr }}
{{ $imgSrc := $img.RelPermalink }}
{{ with .Site.GetPage . }}
<h1>{{ .Title }}</h1>
<img src="{{ $imgSrc }}">
<p>{{ .Content }}</p>
{{ end }}
{{ end }}
I tried to cast the type of `.` to Site. How can I use the string that is stored within `.` to call `.Site.GetPage`?
</details>
# 答案1
**得分**: 1
在范围内,`.` 指的是当前正在读取的数组的当前值。您需要使用 `$.` 而不是 `.` 来[访问全局上下文][1]:
```go
{{ $array := slice "benefits" "faq" }}
{{ range $array }}
{{ with $.Site.GetPage . }}
<h1>{{ .Title }}</h1>
<p>{{ .Content }}</p>
{{ end }}
{{ end }}
英文:
Inside the range, .
refers to the current value of the array being read. You need to use $.
instead of .
to access the global context:
{{ $array := slice "benefits" "faq" }}
{{ range $array }}
{{ with $.Site.GetPage . }}
<h1>{{ .Title }}</h1>
<p>{{ .Content }}</p>
{{ end }}
{{ end }}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论