User's Guide

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:

local templet = require("templet")

local temp = templet.loadstring([[
|for i = 1, 10 do
|  if i > 5 then
Hello, World!
|  end
|end
]])

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

This creates a template object, which is then rendered:

local result = temp()
io.write(result)
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:

local temp = templet.loadstring([[${hello}, ${world}!]])
print(temp({hello = "Hallo", world = "Welt"}))
print(temp({hello = "你好", world = "世界"}))
Hallo, Welt!
你好, 世界!

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.

local temp = templet.loadstring([[
|for i = 1, 3 do
double x${i} = ${math.sqrt(i)};
|end
]])
temp({math = math}, io.write)
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:

temp({math = math}, function(chunk)
  if type(chunk) == "number" and math.floor(chunk) ~= chunk then
    chunk = string.format("%a", chunk)
  end
  return io.write(chunk)
end)
double x1 = 1;
double x2 = 0x1.6a09e667f3bcdp+0;
double x3 = 0x1.bb67ae8584caap+0;

Note that hexadecimal constants require Lua 5.2 or LuaJIT.