Access Config.toml values in theme's partial

Is it possible to access site’s configuration inside a partial?
I am making a custom TOC in layouts\partials\toc.html and would like to have access to site configurations set in config.toml
To do something like this:

{{ $start := .Site.Config.markup.tableOfContents.startLevel }}

Is there a trick to do this?

First, the .Site.Config key refers to privacy and service settings, and looks like this:

.Site.Config
{
  "Privacy": {
    "Disqus": {
      "Disable": false
    },
    "GoogleAnalytics": {
      "Disable": false,
      "UseSessionStorage": false,
      "RespectDoNotTrack": false,
      "AnonymizeIP": false
    },
    "Instagram": {
      "Disable": false,
      "Simple": false
    },
    "Twitter": {
      "Disable": false,
      "EnableDNT": false,
      "Simple": false
    },
    "Vimeo": {
      "Disable": false,
      "EnableDNT": false,
      "Simple": false
    },
    "YouTube": {
      "Disable": false,
      "PrivacyEnhanced": false
    }
  },
  "Services": {
    "Disqus": {
      "Shortname": ""
    },
    "GoogleAnalytics": {
      "ID": ""
    },
    "Instagram": {
      "DisableInlineCSS": false,
      "AccessToken": ""
    },
    "Twitter": {
      "DisableInlineCSS": false
    },
    "RSS": {
      "Limit": -1
    }
  }
}

Second, only some of the configuration settings are exposed to the templates. See:
https://gohugo.io/variables/site/

Third, I recommend creating your own settings under the [params] table, and access them with .Site.Params.foo within your templates.

Finally, if you really want to access site configuration values that aren’t exposed to the template, you can:

{{ $config := os.ReadFile "config.toml" | transform.Unmarshal }}

Which might look like this…

$config
{
  "baseURL": "https://example.org/",
  "languageCode": "en-us",
  "markup": {
    "tableOfContents": {
      "endLevel": 6,
      "ordered": false,
      "startLevel": 3
    }
  },
  "title": "My Site"
}

But this is very fragile because the site configuration file can be named anything, changed at run time, exist in custom directories, be split over multiple files, etc. Don’t do it: go with #3.

1 Like

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