Pass str to .Site.GetPage in hugo

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

Pass str to .Site.GetPage in hugo

问题

  1. Hugo中,我想循环遍历一个字符串切片,然后使用当前字符串调用`.Site.GetPage`
  2. 目前我收到以下错误:
  3. 在<.Site.GetPage>处执行模板失败: 无法在字符串类型中评估字段Site
  4. 我的代码如下:

{{ $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 }}

  1. <details>
  2. <summary>英文:</summary>
  3. Within Hugo, I want to loop over a slice of strings and later use the current string to call `.Site.GetPage`.
  4. Currently I receive the following error:
  5. execute of template failed at &lt;.Site.GetPage&gt;: can’t evaluate field Site in type string
  6. 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 }}

  1. I tried to cast the type of `.` to Site. How can I use the string that is stored within `.` to call `.Site.GetPage`?
  2. </details>
  3. # 答案1
  4. **得分**: 1
  5. 在范围内,`.` 指的是当前正在读取的数组的当前值。您需要使用 `$.` 而不是 `.` 来[访问全局上下文][1]:
  6. ```go
  7. {{ $array := slice "benefits" "faq" }}
  8. {{ range $array }}
  9. {{ with $.Site.GetPage . }}
  10. <h1>{{ .Title }}</h1>
  11. <p>{{ .Content }}</p>
  12. {{ end }}
  13. {{ 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:

  1. {{ $array := slice &quot;benefits&quot; &quot;faq&quot; }}
  2. {{ range $array }}
  3. {{ with $.Site.GetPage . }}
  4. &lt;h1&gt;{{ .Title }}&lt;/h1&gt;
  5. &lt;p&gt;{{ .Content }}&lt;/p&gt;
  6. {{ end }}
  7. {{ 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:

确定