twpayne / chezmoi

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

Templating: Null Check #976

Closed arran-nz closed 3 years ago

arran-nz commented 3 years ago

What exactly are you trying to do?

I'm trying to run a portion of a template when a varaible is defined in ~/.config/chezmoi/chezmoi.toml

What have you tried so far?

{{ .theme.bg }}

{{ eq .theme.bg }}

# If .theme.bg != ""
{{ ne .theme.bg "" }

Where else have you checked for solutions?

Have read this: https://pkg.go.dev/text/template

Output of any commands you've tried with --verbose

$ chezmoi execute-template --verbose "{{ (ne .theme.bg \"\" ) }}"
chezmoi: template: arg1:1:13: executing "arg1" at <.theme.bg>: map has no entry for key "bg"

Additional context

Is it possible to reference a variable which does not exist?

twpayne commented 3 years ago

There are a few options here:

  1. Use the index function which looks up using strings, e.g.

    {{ if (index .theme "bg") }}

    use .theme.bg

    {{ end }}

  2. Tell chezmoi to treat missing variables as empty by setting template.options = ["missingkey=zero"] in your config file.

arran-nz commented 3 years ago

That's great! Thank you for the prompt reply @twpayne !

Can I ask where you found this information?


Also, while I'm here - Thanks for developing and supporting Chezmoi, It's been a tremendous help configuring my machines and I really appreciate how it was designed!

arran-nz commented 3 years ago

Seem to have found the documentation for 2.

twpayne commented 3 years ago

Thanks for your kind words, I'm happy that chezmoi is helpful for you :)

Please re-open this issue if needed :)