Pass str to .Site.GetPage in hugo

huangapple go评论55阅读模式
英文:

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 &lt;.Site.GetPage&gt;: 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 &quot;benefits&quot; &quot;faq&quot; }}
{{ range $array }}
    {{ with $.Site.GetPage . }}
         &lt;h1&gt;{{ .Title }}&lt;/h1&gt;
         &lt;p&gt;{{ .Content }}&lt;/p&gt;
    {{ end }} 
{{ end }}

huangapple
  • 本文由 发表于 2023年5月10日 23:29:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76220234.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定