0

假设数据文件夹中有以下 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 数据文件中使用嵌套进行逻辑组织。

提前致谢。

4

2 回答 2

0

您可以使用嵌套调用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>
于 2021-05-13T06:32:15.567 回答
0

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

在 Markdown 中使用 url 短代码:

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

url短代码的代码:

{{ index .Site.Data.urls (split (.Get 0) ".")}}
于 2021-05-13T13:28:04.243 回答