Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rendering Templates

Templates can be defined in files or directly within a command. The variables can also be defined in the config file or as part of a command.

# This will be the starting path for the templates' output paths
root_dir = "../output/custom_templates"

vars = { my_var = 15 }

# We can define templates directly in the config file
templates = { lit_template = "my_var: {{ my_var }}" }

# Or as files inside a directory
templates_dir = "../templates"

We can then render them singularly, or in groups.

ℹ️ Single templates can be rendered to stdout with the --stdout flag.

Rendering A Single Template

Using A File

If templates_dir is set, all the files in templates_dir can be referenced with their ID, which is the relative path to them from templates_dir.

So if we have this directory structure in our templates_dir:

.
├── abc.j2
└── subdir
    └── nested.j2

We can render the contents of nested.j2 by running

sketch render --id subdir/nested.j2 from_template_file.yaml

However, we can also render content from any file, by using the -f flag. In this case, the relative paths will be resolved from the cwd.

Example:

sketch render -f tests/custom_templates/single_file.j2 from_single_file.yaml

From A Config Definition

Templates can be defined inside the configuration file:

templates = { lit_template = "my_var: {{ my_var }}" }

sketch render --id lit_template from_config_template.yaml

From Literal Definition

...or directly as part of the command:

sketch --set location="Isengard" render --content "they're taking the hobbits to {{ location }}!" from_literal.txt

Rendering Presets

Templates can also be defined in groups, which can be rendered all at once starting from the same root_dir.

This is how groups are defined:

# A group of templates that will be rendered together
templating_presets.test = [
  # Full path to the template file from `templates_dir`
  { template = "subdir/nested.j2", output = "new_dir/nested.yaml" },

  # Only using the global variables
  { template = "lit_template", output = "with_global_var.yaml" },

  # Using a local override
  { template = "lit_template", output = "with_override.yaml", context = { my_var = 20 } },

  # Defining a literal template
  { template = { name = "literal_inlined", content = "my_var: {{ my_var }}" }, output = "literal_inlined.yaml" },
]

When we run the command

sketch render-preset test

These templates will be rendered together, so that the output of the specified root_dir will look like this:

.
├── literal_inlined.yaml
├── new_dir
│   └── nested.yaml
├── with_global_var.yaml
└── with_override.yaml