hugo - 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>
推荐阅读
- javascript - 如何获取页面上图像样本的数据?
- javascript - javascript中的http请求对象参数无法识别
- mysql - 雄辩的 groupBy 问题和从多个表中选择列
- python - 如何以多个同时块下载一个大文件并将它们保存到 Python 中的同一个文件中?
- sql-server - 从长字符串中提取字符串
- c++ - 双重间接
- c++ - 浏览二叉树后出现一些无用的东西
- android - 在 Android 应用程序之外调用 JWT 安全 REST API
- python - 如何在 pandas Dataframe 中实现我自己的公式?
- python - Python pandas 数据帧转置和列作为索引