Introduction
Templates allow you to change file contents based on the environment. For example, use different email addresses or API keys on different machines. chezmoi uses Go’stext/template syntax extended with Sprig functions.
A file is interpreted as a template if:
- The filename has a
.tmplsuffix - The file is in
.chezmoitemplatesdirectory or its subdirectories
Template data
- Built-in variables in
.chezmoi(e.g.,.chezmoi.os,.chezmoi.hostname) .chezmoidata.$FORMATfiles (read in alphabetical order)datasection in your config file
Creating a template file
- Add with --template
- Convert existing file
- Create manually
~/.local/share/chezmoi/dot_zshrc.tmpl.Editing a template file
edit command opens the source file and checks template syntax when you quit the editor.
Testing templates
- Simple expression
- Test file
- PowerShell
myhostTemplate syntax
Template actions are written inside{{ }}. Text outside is copied literally.
- Variables
- Conditionals
- Removing whitespace
Simple logic
Boolean functions
| Function | Description |
|---|---|
eq | Returns true if first argument equals any other argument |
not | Returns boolean negation |
and | Returns boolean AND (returns first empty arg or last arg) |
or | Returns boolean OR (returns first non-empty arg or last arg) |
Integer comparison functions
| Function | Description |
|---|---|
len | Returns integer length |
eq | arg1 == arg2 |
ne | arg1 != arg2 |
lt | arg1 < arg2 |
le | arg1 <= arg2 |
gt | arg1 > arg2 |
ge | arg1 >= arg2 |
More complicated logic
- Multiple eq arguments
- Chaining operators
Helper functions
chezmoi includes:- All Sprig functions
- Custom chezmoi functions (see reference)
Using .chezmoitemplates
Files in .chezmoitemplates can be included in other templates using the template action:
Creating similar files with shared templates
Create shared template
.chezmoitemplates/alacritty
.chezmoitemplates don’t need .tmpl extension.Passing multiple arguments
- Via config file
- Via dictionary
~/.config/chezmoi/chezmoi.toml
.chezmoitemplates/alacritty
small-font.yml.tmpl