User's Guide

1 Getting started

Templates may contain Lua statements and Lua expressions.

A statement is prefixed with |, and extends to the end of the line:

|for i = 1, 10 do
|  if i > 5 then
Hello, World!
|  end
|end

Note that a statement may be preceded by whitespace only.

An expression is enclosed with ${}, and may appear anywhere on a line:

${hello}, ${world}!

A template is parsed using templet.loadstring:

Alternatively, a template is loaded from a file using templet.loadfile.

This creates a template object, which is then rendered:

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

By default, a template is rendered in the global environment (_G), i.e. variables in the template reference global variables. To substitute variables with values, the environment may be set by passing a table as the first argument:

Hallo, Welt!
你好, 世界!

2 Using an output function

A template is rendered and returned as a string by default. Alternatively, an output function may be specified as the second argument, which is repeatedly called for the set of chunks that yield the rendered template.

double x1 = 1;
double x2 = 1.4142135623731;
double x3 = 1.7320508075689;

Suppose we wish to substitute floating-point values in a template using hexadecimal floating-point constants, which are an exact representation of binary values. We pass an output function that checks whether a chunk is a floating-point number, and converts to its hexadecimal representation:

double x1 = 1;
double x2 = 0x1.6a09e667f3bcdp+0;
double x3 = 0x1.bb67ae8584caap+0;

Note that hexadecimal constants require Lua 5.2 or LuaJIT.

3 Including template files

In this example we will implement an include function that evaluates template files included within a template.

templet.loadfile loads template files relative to the current directory. Instead we call package.searchpath with package.path to determine the absolute path of a template file from the Lua modules path, both for loading the main and included template files.

Suppose we have a template file test/included.lua:

We include test/included.lua in the template file test/main.lua:

We evaluate test/main.lua using the function defined above:

print("Ciao, mondo!")
print("Ciao, mondo!")
print("Ciao, mondo!")