Notch Templates
Template Syntax
Three content types: text, expressions, commands
Every byte of a template falls into one of three categories.
Literal text
Anything not matched by an expression or command marker is literal text. It is written to the output verbatim, including whitespace and newlines.
Hello, world!
renders as Hello, world!.
Expressions
The marker ${ ... } evaluates the contents as a Notch expression and substitutes the result into the output. The bracketed content goes through the full Notch parser, so any Notch expression form is allowed.
2 + 2 = ${ 2 + 2 }
renders as 2 + 2 = 4.
Expressions can reference bindings the caller passes to renderTemplate or renderString:
Hello, ${ name }!
with Map.of("name", "world") renders as Hello, world!.
A null value renders as nothing. An unknown name is an error: rendering fails with unknown variable.
There is no escape for ${ in literal text. To output ${ as text, put it in a #raw block (see Built-in Commands).
HTML escaping
The result of an expression is HTML-escaped. The engine replaces &, <, >, " and ' with &, <, >, " and '.
<p>${ comment }</p>
with comment set to <script>alert('hi')</script> renders as:
<p><script>alert('hi')</script></p>
To output HTML without escaping, give the template a RawString (edu.montana.notch.templates.runtime.RawString). The engine writes its content as is:
templates.renderString("${ html }", Map.of("html", new RawString("<b>bold</b>"))); // "<b>bold</b>"
A helper class that implements NotchTemplateHelper also gives templates a raw(value) function that returns a RawString. See helper in Built-in Commands.
Only output HTML without escaping when you trust its source.
Commands
A line that starts with # followed at once by a command name is a template command. Commands drive control flow, layout, variable binding, and other directives.
<ul>
#for item in items
<li>${ item }</li>
#end
</ul>
with Map.of("items", List.of("a", "b", "c")) renders as:
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
The rules for a command line:
- Spaces or tabs before the
#are allowed. Use them to indent commands. - There is no space between
#and the command name.#foris a command.# foris not a command. The engine writes that line to the output as literal text, so a loop variable on the next lines is then anunknown variable. - The rest of the line, up to the newline, holds the command arguments.
- A command line writes nothing to the output, not even its newline.
- A command must start the line. Text before the
#makes the#literal text:${ x } #if truewrites ` #if true`. - A
#that is not followed by a name, such as# heading, is literal text. #followed by a name that is not a registered command is an error:unknown command.
See Built-in Commands for the full list.
See also
- Built-in Commands for the 14 commands shipped with the engine.
- Custom Commands for adding your own.