NAME
template/sluz - Smarty-like templates for ZuzuScript.
SYNOPSIS
from template/sluz import Sluz;
const s := new Sluz();
s.assign("name", "Ada");
s.assign_all({ items: [ "one", "two" ] });
s.add_modifiers(trim: function (v) { return trim("" _ v); });
say( s.parse_string("Hello {$name|escape}") );
const t := s.compile_string("Hello {$name|escape}");
say( t.render({ name: "Ada" }) );
say( t.render({ name: "Bob" }) );
DESCRIPTION
template/sluz is a ZuzuScript port of Scott Baker's Template::Sluz template language. It keeps the familiar Sluz syntax for variables, modifiers, conditionals, loops, includes, literals, and comments, but uses explicit lexical modifier registration instead of looking up Perl subs in main::.
DEFAULT MODIFIERS
Each new Sluz instance registers these modifiers by default:
escapeEscape scalar output. The default mode is
html, which escapes ampersands, angle brackets, and quotes.escape:"xml"uses XML entity names,escape:"url"percent-encodes the value for a URL component, andescape:"js"emits a quoted JavaScript string literal.noescapeReturn the value unchanged and mark the expression as explicitly not requiring automatic escaping.
rawAlias for
noescape.defaultReturn a fallback value when the input is
nullor an emptyString.countReturn the size of an
Array,Bag,Set,Dict, orPairList, or a scalar count for other values.joinJoin an
Array,Bag, orSetwith a separator, defaulting to", ".Arrayorder is preserved.BagandSetoutput order is not guaranteed. Other values are stringified.ucUppercase the value. Alias:
upper.lcLowercase the value. Alias:
lower.upperUppercase the value.
lowerLowercase the value.
ucfirstUppercase the first character of the value.
lengthReturn the string length of the value.
substrReturn a substring using
substr(value, start, length?)semantics.replaceReplace all occurrences of a string.
firstReturn the first element of an
Array, or the first character of a scalar value.lastReturn the last element of an
Array, or the last character of a scalar value.trimTrim leading and trailing whitespace.
normalizeTrim leading and trailing whitespace, then replace each internal run of whitespace with a single space character.
s.add_modifiers can override any of these. s.unset_modifiers removes ordinary modifiers, but escape, noescape, and raw are reset to identity functions instead of becoming undefined.
EXPORTS
Classes
Sluz({ auto_escape?: Boolean|String, base_dir?: Path|Array })Constructs a renderer.
auto_escapedefaults to false. If true, it uses HTML escaping. It may also behtml,xml,url, orjs.base_dircontrols relative template and include lookup. It may be a singlestd/io::Pathor an orderedArrayofPathobjects; the first existing file wins.s.assign(String name, value)Assign one template variable.
s.assign_all(Dict|PairList values)Assign several template variables.
s.add_modifiers(... PairList modifiers)Register named modifiers or callable functions. Registered modifiers override built-ins, including
escape.s.unset_modifiers(String name, ...)Remove modifiers. Removing
escape,noescape, orrawreplaces that modifier with an identity function so explicit and automatic escaping hooks remain defined.s.compile(Path|String file)Load and parse a template file immediately, returning a
CompiledTemplate. The root file is not re-read by laterrendercalls.parent_tplis aparsefeature and is not applied bycompile.s.compile_string(String template)Parse a template string immediately, returning a
CompiledTemplate.s.parse_string(String template)Render a template string.
s.parse(String file, String parent?)Render a template file. If
parentors.parent_tpl()is set, the parent template is rendered with__CHILD_TPLbound to the child file.s.fetch(...)Alias for
parse.s.display(...)Prints the result of
parse.s.display_string(String template)Prints the result of
parse_string.s.parent_tpl(),s.parent_tpl(value)Get or set the default parent template.
s.set_delimiters(String open, String close)Set one-character template delimiters.
CompiledTemplateA parsed template returned by
Sluz.compileorSluz.compile_string.t.render(Dict|PairList values?)Render the compiled template. Values passed to
rendertemporarily overlay the variables assigned on the owningSluzinstance; missing variables fall back to values set withassignandassign_all. If the same key appears more than once in aPairList, the later value wins.Compiled templates use the owning
Sluzinstance's current modifiers,auto_escape,base_dir, and fallback assignments at render time. The template delimiters are frozen at compile time and are used for the root template and any compiled includes.Includes are resolved at render time, so dynamic include expressions may select different files on different renders. Each resolved include file is parsed on first use and cached by path for that compiled template; later renders reuse the cached parsed include and do not observe changes to that included file.
ERRORS
template/sluz throws structured exceptions. All module exceptions inherit from SluzException, which inherits from Exception. SluzException provides get_code() and get_details() accessors; get_code() returns the stored numeric legacy Sluz error code when the exception represents a template-language error, and null otherwise. get_details() currently returns an empty Dict. The raw message slot stores only the bare error message; to_String adds the template/sluz prefix and optional code.
The hierarchy is:
SluzExceptionBase class for all exceptions thrown by this module.
SluzUsageExceptionErrors caused by invalid API usage or renderer configuration.
SluzArgumentExceptionInvalid argument shapes, such as passing something other than
DictorPairListtoassign_allorCompiledTemplate.render.SluzConfigurationExceptionInvalid renderer options, such as
auto_escapeorbase_dirvalues.SluzDelimiterExceptionInvalid delimiter configuration.
SluzLoadExceptionTemplate path lookup and loading errors.
SluzTemplateExceptionErrors found while parsing or rendering Sluz template content.
SluzSyntaxExceptionTemplate syntax and block structure errors.
SluzExpressionExceptionTemplate expression parsing and evaluation errors.
SluzIncludeExceptionInvalid include tags.
SluzModifierExceptionUnknown or invalid modifiers.
SluzEscapeExceptionInvalid escaping modes.
SluzInternalExceptionUnexpected internal renderer states.
to_String returns the same text as stringifying the exception, using module-prefixed strings such as template/sluz: ... or template/sluz error #18933: ....
COPYRIGHT AND LICENCE
This port is copyright Toby Inkster.
It is based on Template::Sluz by Scott Baker and is free software under the terms of the GNU General Public License version 3 or later.