Templates Overview
chezmoi executes templates using Go’stext/template package. Templates allow you to create dynamic configuration files that adapt to different machines, operating systems, and environments.
Basic Concepts
Templates are files with a.tmpl suffix in the source state. chezmoi processes these files and outputs the result to the destination.
Example
~/.local/share/chezmoi/dot_gitconfig.tmpl
Template Execution
The result of template execution is treated differently depending on the target type:For Files
- If the result is an empty string, the file is removed
- Otherwise, the target file contents are the result
For Symlinks
- Leading and trailing whitespace are stripped from the result
- If the result is an empty string, the symlink is removed
- Otherwise, the target symlink target is the result
Template Options
chezmoi executes templates usingtext/template’s missingkey=error option by default, which means that misspelled or missing keys will raise an error.
This can be overridden by setting options in the configuration file:
~/.config/chezmoi/chezmoi.toml
missingkey=default- Use the default behaviormissingkey=error- Return an error on missing keys (default)missingkey=zero- Use the zero value for missing keysmissingkey=invalid- Print<no value>for missing keys
Template.Option.
Template Syntax
Basic Substitution
Comments
Whitespace Control
Conditionals
Loops
Variables
Comparison Operators
Boolean Operators
Template Functions
chezmoi provides all standardtext/template functions, all Sprig functions, and many additional functions.
See Template Functions for a complete list.
Common Functions
Template Variables
chezmoi provides automatically-populated variables accessible via.chezmoi:
Template Directives
File-specific template options can be set using directives:Custom Delimiters
script.sh.tmpl
Line Endings
Encoding
Practical Examples
OS-Specific Configuration
dot_bashrc.tmpl
Machine-Specific Configuration
dot_config_app_config.toml.tmpl
Using Custom Data
.chezmoidata.yaml
run_once_install-packages.sh.tmpl
Using Secrets
dot_config_app_credentials.ini.tmpl
Error Handling
Templates will stop execution if an error occurs:Testing Templates
Usechezmoi execute-template to test template expressions:
Performance Tips
- Cache expensive operations: Store results in variables
- Avoid repeated function calls: Call once and store
- Use includes wisely: Don’t include large files multiple times
- Minimize external calls: Group
outputcalls when possible
Related Pages
- Template Functions - All available functions
- Template Variables - Built-in variables
- Template Directives - File-specific options
- Password Manager Functions - Secret management