英文:
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: "image 1 caption"
- image: image_2.jpg
caption: "image 2 caption"
I want to display just the first one, so I use the following:
{{ $image := .Resources.GetMatch (printf "**%s" (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 "partials/content/figure.html" at <0>: can'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 := "" }}
{{ 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 }}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论