minitemplator

A compact template engine for HTML.

Usage no npm install needed!

<script type="module">
  import minitemplator from 'https://cdn.skypack.dev/minitemplator';
</script>

README

MiniTemplator

MiniTemplator is a compact template engine primarily used for generating HTML output.

Template syntax

Variables:

${variableName}

Blocks:

<!-- $beginBlock blockName -->
  ... block content ...
<!-- $endBlock blockName -->

Conditional statements:

<!-- $if condExpr -->
  ...
<!-- $elseIf condExpr -->
  ...
<!-- $else -->
  ...
<!-- $endIf -->

Include a subtemplate:

<!-- $include fileName -->

Principles

  • Blocks can be nested.
  • Conditions are JavaScript expressions that use condition variables.
  • Subtemplates can include other subtemplates.

Phases

There are two phases when using MiniTemplator templates.

Phase 1: Loading, parsing and caching

When a template is parsed, condition expressions are evaluated, conditional statements are resolved and subtemplates are included. A template is normally loaded and parsed only once and then used many times. A parsed template can be cached in memory for later re-use.

Phase 2: Output document buildup

In the second phase, template variables are set and blocks are added. When the document buildup is complete, evenrything is merged into a HTML string, which is the output of the template engine.

Variables

There are two kinds of variables.

Condition variables

Condition variables are used in $if and $elseIf statements.

  • Condition variables are used at the time a template is loaded and parsed.
  • For each set of condition variable values, a separate parsed template object is cached.

Template variables

Template variables are used to place content into the template.

  • Template variables are used when applying a parsed template to generate output.
  • When a template variable is used within a block, it must be set before the addBlock() method for the block is called.
  • The values undefined and null are converted into an empty string.

Short form for conditional statements

When the shortFormEnabled option is set to true, the following alternative form can be used for conditional statements:

<$? condExpr>
  ... content for "if" case ...
<$: condExpr>
  ... content for "elseIf" case ...
<$:>
  ... content for "else" case ...
<$/?>

Example:

<$?de> Hallo Welt!
<$:fr> Bonjour le monde!
<$:it> Ciao mondo!
<$:  > Hello world!
<$/?>