twpayne / chezmoi

Manage your dotfiles across multiple diverse machines, securely.
https://www.chezmoi.io/
MIT License
13.4k stars 493 forks source link

Dynamic variable in template #1947

Closed rogueai closed 2 years ago

rogueai commented 2 years ago

What exactly are you trying to do?

Hi, I'm trying to setup a way to select a specific set of data based on a variable, in my mind I have some similar to this:

# .chezmoidata.toml

[theme]
  name = "dark"
  [dark]
    color = "black"
  [light]
    color = "white"

Then I would like to use this config in a template like so:

background-color: {{ .theme.<.theme.name>.color ))

Basically, expanding a variable to be used as a variable name itself, without relying on conditional logic in all my templates that would need to be updated every time I add an extra set of config variables.

Apologies if this sounds like a stupid question, but I tried to skim over the docs and couldn't find a way to achieve this.

twpayne commented 2 years ago

So there are two things happening here which likely explain why you're not getting the result you want.

Firstly, in TOML, you have to spell out the explicit hierarchy in keys, it's not like YAML (which uses indentation). In short, your .chezmoidata.toml needs to look like this:

[theme]
  name = "dark"
  [theme.dark]
    color = "black"
  [theme.light]
    color = "white"

Secondly, for dynamic lookups in templates, you need to use the index function which is a builtin function in text/template. So your final code would look something like:

background-color: {{ (index .theme .theme.name).color }}

If your theme has multiple values, then I would recommend creating a template variable for it:

{{- $theme := index .theme .theme.name -}}
background-color: {{ $theme.color }}
rogueai commented 2 years ago

Excellent, this is precisely what I was looking for, thanks!

twpayne commented 2 years ago

Great! You'll probably also want to put the theme.name variable in the machine-specific config file (~/.config/chezmoi/chezmoi.toml) while keeping the theme data in the data file (~/.local/share/chezmoi/.chezmoidata.toml).

Closing as this seems to be resolved, please re-open if needed.