ilusm.dev

tmpl

Template engine with Handlebars-style syntax - render {{variable}} interpolation, {{#each list}}...{{/each}} loops (exposes item and idx), {{#if cond}}...{{else}}...{{/if}} conditionals, {{> partialName}} includes, and dot-path context lookups like {{user.name}}.

Load with: use tmpl

What this module does

tmpl scans a template string character by character looking for {{...}} expressions. Variables are looked up via a dot-path resolver against the context object. Loops iterate over lists injecting item and idx into the child context. Conditionals use a JS-style truthiness check (nil, false, 0, empty string, and empty list are falsy). Partials are registered on the context under _partials.

Quick example

use tmpl

ctx = {
    name: "Alice",
    items: ["apple", "banana", "cherry"],
    show_footer: tru,
    user: {role: "admin"}
}

tpl = "Hello {{name}}!\n{{#each items}}- {{idx}}: {{item}}\n{{/each}}{{#if show_footer}}Footer{{/if}}"

out = tplrn(tpl, ctx)
prn(out)

# Dot-path access
ctx2 = {user: {name: "Bob", age: 30}}
prn(tplrn("{{user.name}} is {{user.age}}", ctx2))

# Register and use partials
ctx3 = tplpr(ctx, "header", "<h1>{{name}}</h1>")
prn(tplrn("{{> header}}", ctx3))

Functions

Rendering

tplrn(src, ctx) / tmpl.run(src, ctx)

Renders template string src against context object ctx. Returns the rendered string. Supports variable interpolation, each loops, if/else conditionals, and partial includes.

Context helpers

tplget(ctx, path) / tmpl.get(ctx, path)

Resolves a dot-separated path (e.g. "user.address.city") through the context object. Returns nil if any step is absent.

tplpr(ctx, name, src) / tmpl.par(ctx, name, src)

Registers a partial template named name on the context under _partials. Returns the updated context. Invoke with {{> name}} in templates.

Notes

  • Loops expose item (current element) and idx (0-based index) in child context.
  • Truthiness: nil, fls, 0, "", and empty lists are falsy.
  • Requires txt and trl.