Is it possible to store a dictionary in a .chezmoi.yaml.tmpl data variable? #3107
-
I've got confused by a somewhat basic chemoi variable type question: what data types can I store in chezmoi data? I'd like to programmatically generate a dictionary and then use it in other templates (below is an example of a manually generated dictionary) .chezmoi.yaml.tmpl
But then when I try to use it
I get a type mismatch error
and just importing it
gives me Tangentially related: is it possible to export a variable from a template? Then I could stuck some common |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Absolutely. I take advantage of this in my .chezmoitemplates/programs.tmpl to cache all of my The main thing to know is that only strings can return from templates, so you have to convert it to JSON ( For your example, you would need to do data:
mydict: #{{ dict "key" 12 | toJson }} I’m using TOML for my config file, which makes things somewhat uglier for keeping data clean between two different calls of |
Beta Was this translation helpful? Give feedback.
-
Thanks, that's the part I was missing, I thought looking at the default variables https://www.chezmoi.io/reference/templates/variables/ it had strings and integers and objects, not just strings, so I thought it wasn't as limited to need a serialization Also, I mistakenly thought I could use lists there because of this test define
use: "works", get
(but no
this is exactly my use case, and it's nice to know that the results are cache as I thought I'd need to move it to data and Although the original example doesn't work with # fails↓ with at <fromJson>: wrong type for value; expected string; got map[string]interface {}
#‹ $x := .mydict | fromJson ›
# succeeds↓
#‹ $x := .mydict ›
#‹ get $x "key" › (and minor typo |
Beta Was this translation helpful? Give feedback.
Absolutely. I take advantage of this in my .chezmoitemplates/programs.tmpl to cache all of my
lookPath
operations (some of them are used in multiple templates; I know that chezmoi caches the result).The main thing to know is that only strings can return from templates, so you have to convert it to JSON (
| toJson
) and when you import it, you need to convert it from JSON ($x := importTemplate "programs.tmpl" | fromJson
).For your example, you would need to do
I’m using TOML for my config file, which makes things somewhat uglier for keeping data clean between two different calls of
chezmoi init
as you can see in https://github.com/halostatue/dot…