如何在数组对象的元素中显示存储为页面资源的图像?

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

How to display an image stored as a page resource when it's an element of an array of objects?

问题

我的翻译如下:

我的前置内容中的图像存储方式如下:

images:
  - image: image_1.jpg
    caption: "图像1说明"
  - image: image_2.jpg
    caption: "图像2说明"

我想只显示第一个图像,所以我使用以下代码:

{{ $image := .Resources.GetMatch (printf "**%s" (index .Params.images 0).image) }}

奇怪的是,只有在本地的hugo服务器运行时,这段代码才能正常工作。一旦我停止并重新启动服务器,网站就无法重新构建,出现以下错误:

...执行模板失败:template: partials/content/figure.html:7:70: 在“partials/content/figure.html”中执行时出错:<0>:无法评估字符串类型中的图像字段

我只想能够访问images[0].image。如何使其正常工作?

英文:

Images in my front matter are stored like this:

images:
  - image: image_1.jpg
    caption: &quot;image 1 caption&quot;
  - image: image_2.jpg
    caption: &quot;image 2 caption&quot;

I want to display just the first one, so I use the following:

{{ $image := .Resources.GetMatch (printf &quot;**%s&quot; (index .Params.images 0).image) }}

Oddly, this only works if I add the .image part while my local hugo server is running. As soon as I stop and start it again, the site fails to rebuild with the following error:

... execute of template failed: template: partials/content/figure.html:7:70: executing &quot;partials/content/figure.html&quot; at &lt;0&gt;: can&#39;t evaluate field image in type string

I just want to be able to access images[0].image. How can I make this work?

答案1

得分: 1

原文翻译如下:

原来我在其他内容类型中,images在前置数据中仍然是简单的数组,而不是对象数组。这导致了我的构建错误。为了解决这个问题,我使用了以下方法,正如这里所推荐的:

{{ $image := "" }}
{{ if reflect.IsMap (index .Params.images 0) }}
  {{ $image = .Resources.GetMatch (printf "**%s" (index .Params.images 0).image) }}
{{ else }}
  {{ $image = .Resources.GetMatch (printf "**%s" (index .Params.images 0)) }}
{{ end }}
英文:

It turns out I had some other content types in which images in front matter were still simple arrays, rather than arrays of objects. This was causing my build error. To solve the problem, I used the following, as was recommended here:

{{ $image := &quot;&quot; }}
{{ if reflect.IsMap (index .Params.images 0) }}
  {{ $image = .Resources.GetMatch (printf &quot;**%s&quot; (index .Params.images 0).image) }}
{{ else }}
  {{ $image = .Resources.GetMatch (printf &quot;**%s&quot; (index .Params.images 0)) }}
{{ end }}

huangapple
  • 本文由 发表于 2023年2月9日 19:53:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75398217.html
匿名

发表评论

匿名网友

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

确定