modules/template/sluz.zzm

template-sluz-0.0.1 documentation

Package

Name
template-sluz
Version
0.0.1
Uploaded
2026-07-09 22:36:42
Dependencies
Metadata
zuzu-distribution.json
Archive
Download .tar.gz

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:

  • escape

    Escape 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, and escape:"js" emits a quoted JavaScript string literal.

  • noescape

    Return the value unchanged and mark the expression as explicitly not requiring automatic escaping.

  • raw

    Alias for noescape.

  • default

    Return a fallback value when the input is null or an empty String.

  • count

    Return the size of an Array, Bag, Set, Dict, or PairList, or a scalar count for other values.

  • join

    Join an Array, Bag, or Set with a separator, defaulting to ", ". Array order is preserved. Bag and Set output order is not guaranteed. Other values are stringified.

  • uc

    Uppercase the value. Alias: upper.

  • lc

    Lowercase the value. Alias: lower.

  • upper

    Uppercase the value.

  • lower

    Lowercase the value.

  • ucfirst

    Uppercase the first character of the value.

  • length

    Return the string length of the value.

  • substr

    Return a substring using substr(value, start, length?) semantics.

  • replace

    Replace all occurrences of a string.

  • first

    Return the first element of an Array, or the first character of a scalar value.

  • last

    Return the last element of an Array, or the last character of a scalar value.

  • trim

    Trim leading and trailing whitespace.

  • normalize

    Trim 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_escape defaults to false. If true, it uses HTML escaping. It may also be html, xml, url, or js. base_dir controls relative template and include lookup. It may be a single std/io::Path or an ordered Array of Path objects; 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, or raw replaces 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 later render calls. parent_tpl is a parse feature and is not applied by compile.

    • 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 parent or s.parent_tpl() is set, the parent template is rendered with __CHILD_TPL bound 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.

  • CompiledTemplate

    A parsed template returned by Sluz.compile or Sluz.compile_string.

    • t.render(Dict|PairList values?)

      Render the compiled template. Values passed to render temporarily overlay the variables assigned on the owning Sluz instance; missing variables fall back to values set with assign and assign_all. If the same key appears more than once in a PairList, the later value wins.

      Compiled templates use the owning Sluz instance'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:

  • SluzException

    Base class for all exceptions thrown by this module.

    • SluzUsageException

      Errors caused by invalid API usage or renderer configuration.

      • SluzArgumentException

        Invalid argument shapes, such as passing something other than Dict or PairList to assign_all or CompiledTemplate.render.

      • SluzConfigurationException

        Invalid renderer options, such as auto_escape or base_dir values.

        • SluzDelimiterException

          Invalid delimiter configuration.

      • SluzLoadException

        Template path lookup and loading errors.

    • SluzTemplateException

      Errors found while parsing or rendering Sluz template content.

      • SluzSyntaxException

        Template syntax and block structure errors.

      • SluzExpressionException

        Template expression parsing and evaluation errors.

      • SluzIncludeException

        Invalid include tags.

      • SluzModifierException

        Unknown or invalid modifiers.

        • SluzEscapeException

          Invalid escaping modes.

      • SluzInternalException

        Unexpected 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.