首页 > 解决方案 > 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 数据文件中使用嵌套进行逻辑组织。

提前致谢。

标签: hugohugo-shortcode

解决方案


您可以使用嵌套调用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>

推荐阅读