Enables the parsing of basic templates.
Also check out slt2, which is about a million times better!
-
Template.Parse ( template, data )
Parses a template string.
template
is the template string.data
is a table containing the data to apply to the template. Returns the resulting output string.A table is also returned. If any template tags throw an error, the error string will be added to this table.
-
Template.ParseFile ( file, data )
Parses a template from the contents of a file.
file
is the name of the file to get the template from.data
is a table containing the data to apply to the template. Returns the resulting output string.A table is also returned. If any template tags throw an error, the error string will be added to this table.
When a template is parsed, the parser looks for tags. Tags are portions of
the template contained within double-curly brackets ({{ }}
).
The character (\
) can be used to escape characters with special meaning,
such as opening or closing tag brackets, or escape characters.
Other than these, portions of a template are interpreted literally.
The content of a tag is interpreted as a Lua function. The values returned by the function construct the tag's output string. Values are converted to strings, then concatenated together. The exception is tables, which are instead recursed.
Tags have customized environments. Most global variables are removed for safety reasons. The following variables are either added back in, or reimplemented:
-
print ( ... )
Arguments are converted to strings and appended to the tag's output. No separators are added between arguments. Works as an alternative to returning values. Tables are recursed in the same way.
Values in the data table (the one passed to the Parse function) are also added to the environment, so that they may be accessed directly. This is where the real magic of templates happens. For example, the data table,
{ fruit = "apple" }
along with the tag,
{{return fruit}}
will output the string "apple".
If the tag throws an error, and a default
entry is specified in the data
table, then the value of that entry will be outputted instead of an empty
string.
template = [[Hello, {{return user}}! How are you?]]
data = { user = "Alice" }
print( Template.Parse(template, data) )
--> "Hello, Alice! How are you?"
template = [[Escape characters with the "\\" character!]]
print( Template.Parse(template) )
--> "Escape characters with the "\" character!"
template = [[Replace content using the \{{tag}} format!]]
print( Template.Parse(template) )
--> "Replace content using the {{tag}} format!"
template = [[Replace content using the {{return "{{tag\}}"}} format!]]
print( Template.Parse(template) )
--> "Replace content using the {{tag}} format!"