Search code examples
hugohugo-shortcode

Hugo - using index with complex key to get data


Assuming the following urls.toml file in data folder:

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

I know that I can access the link value in Group.A in my shortcode like this:

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

But, I would like to access the link in a way similar to the following:

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

The reason for this is to enable me to pass the "Group.A.link" as a parameter to my "url" shortcode within the content markdown like this:

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

Otherwise, I won't be able to use nesting for logical organisation in the urls.toml data file.

Thanks in advance.


Solution

  • After having looked at Hugo's code (Index function) I found a very simple solution. If we want to pass a complex comma-separated key, all we need to do is split it when calling index. Example:

    Using the url shortcode in markdown:

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

    Code of the url shortcode:

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