Getting Started

Load and render your first template

Templates are loaded by a NotchTemplateLoader and rendered through NotchTemplates. Pick a loader, build a NotchTemplates, register the built-in commands, and call renderTemplate.

Picking a loader

Four loaders ship with the engine, in the package edu.montana.notch.templates.loader:

  • DefaultNotchTemplateLoader - the loader that new NotchTemplates() uses. It searches, in this order: the classpath root, templates/ and views/ on the classpath, then templates/ and views/ in the working directory. The first location that has the template wins. If no location has it, the error lists each location.
  • ClasspathNotchTemplateLoader - loads templates as classpath resources. Good for templates bundled inside a JAR. new ClasspathNotchTemplateLoader(Path.of("views")) loads from the views/ folder of the classpath.
  • FileSystemNotchTemplateLoader - loads templates from a directory on disk. Good for templates the user can edit at runtime. It refuses paths outside the directory.
  • InMemoryNotchTemplateLoader - holds templates in a map. Add one with addTemplate(name, content). Good for tests.

All four extend the abstract class NotchTemplateLoader, so you can also write your own.

Building the engine

import edu.montana.notch.templates.BasicNotchTemplateCommands;
import edu.montana.notch.templates.NotchTemplates;
import edu.montana.notch.templates.loader.FileSystemNotchTemplateLoader;
import java.nio.file.Path;

NotchTemplates templates = new NotchTemplates(new FileSystemNotchTemplateLoader(Path.of("templates")));
BasicNotchTemplateCommands.addTo(templates);

BasicNotchTemplateCommands.addTo registers the 14 built-in commands. Without it your templates can use expressions and literal text but no # commands. A # command then fails with unknown command.

Rendering

Suppose templates/greeting.html contains:

Hello, ${ name }!

Then:

String output = templates.renderTemplate("greeting.html", Map.of("name", "world"));
System.out.println(output);

prints Hello, world!. The first argument is the template path, given to the loader as is. The second argument is a map of bindings the template can reference by name.

To render one fragment of a template, add # and the fragment name to the path, for example renderTemplate("contacts.html#rows", vars). See fragment in Built-in Commands.

To render a template that is in a String, use renderString:

templates.renderString("2 + 2 = ${ 2 + 2 }", Map.of());  // "2 + 2 = 4"

See also