Module template-text
This modules exposes function(s) to evaluate textual templates, that is, text which contain references to variables or expressions, or even Lua code statements.
For example:
local engine = require "template-text" local ok, loaded = engine.tload("Hello $(whom)", {}, {whom="Marco"}) ok, text = loaded.evaluate() print(text) -- Hello Marco
You can find more examples in this documentation's menu.
Similar programs are usually referred to as "templat[e|ing] engines" or "pre-processors" (like the examples on the Lua user-wiki this module is largely inspired from).
Briefly, the format for the templates is the following: regular text in the
template is copied verbatim, while expressions in the form $(<var>)
are
replaced with the textual representation of <var>
, which must be
evaluatable in the given environment.
Lines starting with @
are interpreted entirely as Lua code.
For more information and more features see syntax_reference.md and
the examples.
The module's local functions are for internal use, whereas
the "public" module's functions are those documented as module.<...>
.
These are the fields of the table you get by requireing the module.
Info:
- Author: Marco Frigerio
Functions
module.tload () | Loads a template: this is the main function of the module. |
module.template_eval () | Deprecated. |
module.lineDecorator () | Adds prefix/suffix to the text produced by an existing iterator. |
Tables
ExpandedTemplate | An expanded template, resulting from expand() |
LoadResult | A parsed template, bound to an evaluation environment, as returned by tload. |
Local Functions
lines (s) | |
insertLines (text, lines, totIndent) | Copy every string in the second argument into the first, prepending indentation. |
lineDecorator (generator, prefix, suffix) | Decorates an existing string iteration, adding an optional prefix and suffix. |
getErrorAndLineNumber (lua_error_msg) | Parses a line from a Lua error message trying to extract the line number and the error description. |
errHandler (e) | Error handler to be used with xpcall. |
build_error_trace (trace, expanded_template, error_line_num, indent) | Recursively constructs the error trace, a sequence or error messages. |
evaluate (raw_eval_f, template, env, opts, env_override) | Executes the parsed template function. |
expand (template, opts, included_templates) | Generates the rendering code from a user template. |
tload (template, opts, env, included_templates) | Loads the given text-template and binds it to the given environment. |
Functions
- module.tload ()
-
Loads a template: this is the main function of the module.
See the docs of the local function tload which has the same signature.
Returns:
- module.template_eval ()
-
Deprecated. Evaluates the given textual template.
Deprecated, included for backwards compatibility with the older version of this module. It is equivalent to call tload first, and then
evaluate()
on the result. - module.lineDecorator ()
-
Adds prefix/suffix to the text produced by an existing iterator.
See also:
Tables
- ExpandedTemplate
-
An expanded template, resulting from expand()
Fields:
- source The original template text
- code The Lua source code generated from the template, as an array of strings. This is the code that is run when "evaluating" the template. Inspecting this is useful for debugging or to understand how the process works.
- included A by-name map of the expanded included templates
- line_of_code_to_source A int-to-int map, from line of code to the corresponding line in the source template (for internal use - this gets more complex in the case of included templates)
- LoadResult
-
A parsed template, bound to an evaluation environment, as returned by tload.
Fields:
- env The same environment given to tload by the caller
- template The resulting ExpandedTemplate
- evaluate
The function to actually evaluate the template. This is
a closure of the internal evaluate that only takes the
opts
andenv_override
arguments; see their description in evaluate.
Local Functions
- lines (s)
-
Parameters:
- s
Returns:
-
an iterator over the lines of the given string
- insertLines (text, lines, totIndent)
-
Copy every string in the second argument into the first, prepending indentation.
The first argument must be a table. The second argument is either a table
itself (having strings as elements) or a function returning a factory of
a suitable iterator; for example, a function returning 'ipairs(t)', where 't'
is a table of strings, is a valid argument.
Parameters:
- text
- lines
- totIndent
- lineDecorator (generator, prefix, suffix)
-
Decorates an existing string iteration, adding an optional prefix and suffix. The first argument must be a function returning an existing iterator generator, such as a ipairs. The second and last argument are strings, both optional.
Sample usage:
local t = {"a","b","c","d"} for i,v in lineDecorator( function() return ipairs(t) end, "--- ", " ###") do print(i,v) end
Parameters:
- generator
- prefix
- suffix
- getErrorAndLineNumber (lua_error_msg)
-
Parses a line from a Lua error message trying to extract the line number and
the error description.
This function is tailored for errors that may arise when loading and executing a user template.
Parameters:
- lua_error_msg
try to match '[.."
"] : '
Returns:
-
A table with two fields, the linenumber (
linenum
) and the error message (msg
). The line number is set to -1 when it could not be extracted. - lua_error_msg
try to match '[.."
- errHandler (e)
-
Error handler to be used with xpcall. For internal use.
Uses getErrorAndLineNumber on each line of the original error message as well as the stacktrace, in the attempt of providing good information about the problem.
Parameters:
- e
Returns:
-
A table with two fields:
cause
andstacktrace
. The first is the return value of getErrorAndLineNumber invoked with the error message. The second is an array, whose elements are the return value of getErrorAndLineNumber for each line of the stacktrace where a line number could be extracted. - build_error_trace (trace, expanded_template, error_line_num, indent)
-
Recursively constructs the error trace, a sequence or error messages.
Recursion is used due to the template inclusion feature: this function tries to trace back the source of the error even in the case of nested templates, at arbitrary depth (e.g. template t1 includes t2 which includes t3, ..., tn, and the error is in tn).
Parameters:
- trace The table holding the sequence (array) of messages
- expanded_template The ExpandedTemplate table in which the error occurred
- error_line_num The number of the line of code where the error occurred
- indent The current value of indentation for the formatting of the error messages
- evaluate (raw_eval_f, template, env, opts, env_override)
-
Executes the parsed template function. For internal use.
Parameters:
- raw_eval_f The function returned by Lua's load on the code obtained from the template
- template The ExpandedTemplate table
- env The environment (table) that the template was loaded with
- opts A table with options:
- returnTable if true, the return value is an array of text lines, otherwise a single string.
- env_override An optional table that overrides matching entries in the bound environment
Returns:
- A boolean flag indicating success
- In case of success, the text of the evaluated template, as a single string or as an array of lines. In case of failure, an array of lines with error information.
- expand (template, opts, included_templates)
-
Generates the rendering code from a user template.
This is the function that "implements the syntax" of this template engine.
Parameters:
- template
- opts
- included_templates
- tload (template, opts, env, included_templates)
-
Loads the given text-template and binds it to the given environment.
This function produces an object (LoadResult) that can be evaluated into the final text. It checks for syntax errors and tries to produce precise error messages.
Parameters:
- template the text-template, as a string
- opts non-mandatory options, a table with these fields:
- indent number of blanks to be prepended before every output line; this applies to the whole template, relative indentation between different lines is preserved
- xtendStyle
if true, variables are matched with the pattern
«<var>»
- instead of the default$(<var>)
- env A table which shall define all the upvalues being referenced in the given template
- included_templates A by-name map of the templates that are included by
template
. Optional.Returns:
- A boolean indicating success/failure (true/false).
-
In case of success, a table LoadResult whose primary field is a
function to actually evaluate the template into text. In case of errors,
an array of strings with information about the error, including a
line number, when possible.
This function internally calls expand() and then Lua's load().