Module template-text
A module 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 the
syntax reference and
the examples.
The module's local functions are for internal use, whereas
the "public" module's functions are those documented as mAPI.<...>
("module's API").
These are the fields of the table you get by requireing the module.
Info:
- Author: Marco Frigerio
Functions
| mAPI.tload (template, opts, env, included_templates) | Loads the given template and binds it to the given environment. |
| mAPI.template_eval (template, env, opts, included_templates) | Loads and evaluates the given template. |
| mAPI.lineDecorator (generator, prefix, suffix) | Decorates an existing string iteration, adding an optional prefix and suffix. |
Tables
| ExpandedTemplate | The return type of expand() |
| LoadResult | A parsed template, bound to an evaluation environment, as returned by tload. |
Local Functions
| lines (s) | |
| insertLines (text, lines, totIndent) | Copy every line of text in the second argument and append it into the first |
| getErrorAndLineNumber (lua_error_obj) | Parses a line from a Lua error message trying to extract the line number and the error description. |
| errHandler (lua_error_obj) | 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. |
Functions
- mAPI.tload (template, opts, env, included_templates)
-
Loads the given template and binds it to the given environment.
This function produces an object (LoadResult) that can be evaluated into the intended text. It checks for syntax errors and tries to produce precise error messages.
This function is the main entry-point for the module.
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.
-
When available, the ExpandedTemplate computed from the given one.
This function internally calls expand() and then Lua's load(). In case of loading errors (which are typically Lua's syntax errors), the expanded template is available as the third return value, and can be inspected for debugging.
- mAPI.template_eval (template, env, opts, included_templates)
-
Loads and evaluates the given template.
This function is provided for convenience and for backwards compatibility with the older version of this module.
It is equivalent to call tload first, and then the evaluation function on the LoadResult. See those functions for a description of the parameters. Watch out for the different order of
envandopts.Parameters:
- template
- env
- opts
- included_templates
Returns:
- A boolean flag indicating success
- The evaluation result (which is normally text). The text of the error message if the first return value is false.
- mAPI.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) endParameters:
- generator
- prefix
- suffix
Tables
- ExpandedTemplate
-
The return type of expand()
Fields:
- source The original template that was expanded
- 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
optsandenv_overridearguments; 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 line of text in the second argument and append it into the first
Parameters:
- text The destination where the lines will be appended; must be a table
- lines
The source to read the lines from. It must be either an array of
strings or a function returning a factory of a suitable iterator; for
example a function returning
ipairs(t), wheretis a table of strings. - totIndent
A string that is prepended to every line before copying the
line into
text. Normally a sequence of blanks to get the desired indentationThis function is used internally to implement the table-inclusion syntax
${aTable}.
- getErrorAndLineNumber (lua_error_obj)
-
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_obj
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. - errHandler (lua_error_obj)
-
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:
- lua_error_obj
Returns:
-
A table with two fields:
causeandstacktrace. 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; this is filled by this function
- expanded_template The ExpandedTemplate in which the error occurred
- error_line_num
The number of the line of code where the error
occurred, that is the index of
expanded_template.code. - 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.
"Expansion" refers to the text-to-text transformation that turns the user's template into a corresponding Lua program.
This is the function that "implements the syntax" of this template engine, that is, the function that does parsing and transformation of the replacement fields.
Parameters: