Hugo - 使用带有复杂键的索引来获取数据

问题描述

假设数据文件夹中有以下 urls.toml 文件

[Group]
    link = "http://example.com"
    [Group.A]
        link = "http://example.com"

我知道我可以像这样在我的短代码中访问 Group.A 中的链接值:

{{ index .Site.Data.urls.Group.A "link" }}

但是,我想以类似于以下的方式访问该链接

{{ index .Site.Data.urls "Group.A.link" }}

这样做的原因是让我能够将“Group.A.link”作为参数传递给内容降价中的“url”短代码,如下所示:

{{< url "Group.A.link" >}}

否则,我将无法在 urls.toml 数据文件中使用嵌套进行逻辑组织。

提前致谢。

解决方法

您可以使用 index COLLECTION "key" 的嵌套调用来缩小范围。
意思是,

(index (index (index .Site.Data.urls "Group") "A") "link")

考虑到您的 urls.toml 结构会起作用。

诀窍是让它有点动态,所以你不必太担心深度。

下面的代码片段可以作为短代码的潜在起点。但是,它没有任何保护措施。如果出现问题,我建议添加一些检查以获取有意义的错误/警告。

{{ $path := .Get 0 }}
{{/* split the string to have indices to follow the path */}}
{{/* if $path is "A.B.C",$pathSlice wil be ["A" "B" "C"] */}}
{{ $pathSlice := split $path "." }}
{{ $currentValue := .Site.Data.urls }}
{{ range $pathSlice }}
    {{/* recommended homework: check that $currentValue is a dict otherwise handle with defaults and/or warnings */}}
    {{ $currentValue = index $currentValue . }}
{{ end }}

<p>et voila: {{ $currentValue }}</p>
,

在查看了 Hugo 的代码 (Index function) 后,我找到了一个非常简单的解决方案。 如果我们想传递一个复杂的逗号分隔键,我们需要做的就是在调用 index.html 时将其拆分。示例:

在 markdown 中使用 url 短代码:

{{< url "Group.A.link" >}}

网址简码代码:

{{ index .Site.Data.urls (split (.Get 0) ".")}}