A template is a hygienic code substitution: its body is pasted at the call site, then compiled.
Nim Medium · Lesson 1 · On the house
Templates
Code substitution with template, untyped parameters, hygiene, and when to use them. Lesson 1 is free — on the house.
Lessons · Nim Medium · Lesson 1 of 10 · On the house
Templates
Code substitution with template, untyped parameters, hygiene, and when to use them.

Parameters are evaluated where they appear in the body, so untyped blocks can be passed in: template twice(body: untyped) = body; body.
Templates are good for small control-flow helpers (withLock, measure, retry) with zero call overhead.
Variables declared inside are hygienic (renamed) unless marked {.inject.}.
A parameter used twice is evaluated twice; bind it to a let first if it has side effects.
templates
import std/[times, monotimes]
template twice(body: untyped) =
body
body
template measure(label: string, body: untyped) =
let t0 = getMonoTime()
body
let ms = (getMonoTime() - t0).inMilliseconds
doAssert ms >= 0
echo label, " done"
template withValue(v: int, body: untyped) =
let it {.inject.} = v * 10
body
var n = 0
twice: inc n
echo n
measure("sum"):
var s = 0
for i in 1..1000: s += i
echo s
withValue(4):
echo it + 2
Quiz
Quiz
Quiz
Quiz
Check
Match the still for: Templates.
Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.