05 - Templates¶
Learn how to render configuration files from templates using pongo2 syntax.
What You'll Learn¶
- Rendering
.j2template files - Using variables in templates
- Template conditionals (
{% if %}) - Template loops (
{% for %}) - Passing additional vars to templates
Quick Start¶
Check the rendered files:
What It Does¶
- Defines variables for application, server, and database config
- Renders application config with loops and conditionals
- Renders nginx config with optional SSL
- Creates executable script from template
- Renders same template with different variables
Key Concepts¶
Template Action¶
Template Syntax (pongo2)¶
Variables:
Conditionals:
Loops:
Filters:
Passing Additional Vars¶
Override variables for specific templates:
- template:
src: ./templates/config.yml.j2
dest: /tmp/prod-config.yml
vars:
environment: production
debug: false
Template Files¶
config.yml.j2¶
Application configuration with: - Conditional debug settings - Loops over features list - Variable substitution
nginx.conf.j2¶
Web server config with: - Conditional SSL configuration - Dynamic port and paths
script.sh.j2¶
Executable shell script with: - Shebang line - Variable expansion - Command loops
Common Use Cases¶
- Config files - app.yml, nginx.conf, etc.
- Shell scripts - deployment scripts, setup scripts
- Systemd units - service files
- Dotfiles - .bashrc, .vimrc with customization
Testing Templates¶
# Render templates
mooncake run --config config.yml
# View rendered output
cat /tmp/mooncake-templates/config.yml
# Check executable permissions
ls -la /tmp/mooncake-templates/deploy.sh
Next Steps¶
Continue to 06-loops to learn about iterating over lists and files.