【问题标题】:Hugo - using index with complex key to get dataHugo - 使用具有复杂键的索引来获取数据
【发布时间】:2021-05-13 21:39:12
【问题描述】:

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

提前致谢。

【问题讨论】:

    标签: hugo hugo-shortcode


    【解决方案1】:

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

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

    考虑到您的 urls.toml 结构,将可以工作。

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

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

    {{ $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>
    

    【讨论】:

      【解决方案2】:

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

      在 Markdown 中使用 url 短代码:

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

      url短代码的代码:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-25
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 2015-08-30
        • 1970-01-01
        • 2015-06-13
        相关资源
        最近更新 更多