How can I write an if statement in resources.Get Hugo?

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

How can I write an if statement in resources.Get Hugo?

问题

我有以下代码:

{{ with resources.Get .Site.Params.image }}
    <meta property="og:image" content="{{ .Permalink }}" />
{{ end }}

我在config.toml文件中获取了一个图像路径。然而,我现在想通过frontmatter数据来覆盖该文件... 类似于以下伪代码:

{{ if isset .Image }}
{{ $image := .Image }}
{{ else }}
{{ $image := .Site.Params.image }}
{{ end }}
{{ with resources.Get $image }}
...

我该如何编写这个语句?如果你有关于这些语句和语法的好教程,请告诉我!

英文:

I have the following code:

{{ with resources.Get .Site.Params.image }}
    <meta property="og:image" content="{{ .Permalink }}" />
{{ end }}

I get a image path in the config.toml file. However I now want to be able to overwrite the file by frontmatter data... Something like this (in pseudo code):

{{ if isset .Image }}
{{ $image := .Image }}
{{ else }}
{{ $image := .Site.Params.image }}
{{ end }}
{{ with resources.Get $image }}
...

How can I write this statement? Also if you have good tutorials on these statements and syntax let me know!

答案1

得分: 2

使用or函数:

{{ with resources.Get (or .Params.thumbnailImage .Site.Params.ogImage) }}
    <meta property="og:image" content="{{ .Permalink }}" />
{{ end }}
英文:

Use the or function:

{{ with resources.Get (or .Params.thumbnailImage .Site.Params.ogImage) }}
    <meta property="og:image" content="{{ .Permalink }}" />
{{ end }}

答案2

得分: 0

这是我的解决方案:

{{ $ogImage := "" }}
{{ if .Params.thumbnailImage }}
    {{ $ogImage = .Params.thumbnailImage }}
{{ else }}
    {{ $ogImage = .Site.Params.ogImage }}
{{ end }}
{{ $ogImageRender := resources.Get $ogImage }}
{{ with $ogImageRender }}
    <meta property="og:image" content="{{ .Permalink }}" />
{{ end }}
  • := 定义变量并设置初始值
  • = 将变量设置为另一个值
英文:

EDIT: I updated to @brendan solution.


This is my solution:

{{ $ogImage := &quot;&quot; }}
{{ if .Params.thumbnailImage }}
    {{ $ogImage = .Params.thumbnailImage }}
{{ else }}
    {{ $ogImage = .Site.Params.ogImage }}
{{ end }}
{{ $ogImageRender := resources.Get $ogImage }}
{{ with $ogImageRender }}
    &lt;meta property=&quot;og:image&quot; content=&quot;{{ .Permalink }}&quot; /&gt;
{{ end }}
  • := defines variables and set initial value
  • = set variables to another value

huangapple
  • 本文由 发表于 2022年8月26日 21:31:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/73501826.html
匿名

发表评论

匿名网友

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

确定