HUGO

Which method to access values from TOML data?

Hello everyone,

I have this .toml file in my data folder called roman.toml. I need to match the current arabic year / key and display its roman value.

# Roman numerals
2021 = "MMXXI"
2022 = "MMXXII"
2023 = "MMXXIII"
2024 = "MMXXIV"
2025 = "MMXXV"
2026 = "MMXXVI"
2027 = "MMXXVII"
2028 = "MMXXVIII"
2029 = "MMXXIX"
2030 = "MMXXX"

Is index the most suitable method to retrieve a value from this file?

In my footer.html partial I have tried the following code, but it fails and says now.Year must be a string.

  <span class="copyright">
    {{ $year := .Site.Data.roman }}
    {{ index $year now.Year }}
    ** copyright notice here **
  </span>

If I replace now.Year with “2021” for example, it works – but I want this to be dynamic. I’ve been going round in circles reading about functions, ranges, ‘print’ methods and I’m lost!

Your help is much appreciated

{{ index site.Data.roman (string now.Year) }}

Thanks @jmooring! Works perfectly

Would you mind explaining why this works? and if there’s any difference between site.Data vs .Site.Data?

The data keys are strings, but now.Year is an integer. Try it:

{{ printf "%T" now.Year }} 

Note that bare keys are allowed to be composed of only ASCII digits, e.g. 1234 , but are always interpreted as strings.

https://toml.io/en/v1.0.0#keys

Regarding site vs .Site… search this forum. Example:
https://discourse.gohugo.io/t/site-vs-site-any-performance-advantages-of-either/29973/2

1 Like

Understood! Thanks again :slight_smile:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.