Notch Templates
Custom Commands
Adding your own template commands
Template commands are subclasses of NotchTemplateCommand. Register a command with NotchTemplates.addCommand(command) and templates can invoke it just like the built-ins. The command name comes from the constructor: super("upper") makes the command #upper.
Anatomy of a command
A command implementation does three things:
- Parses its arguments in
parseCommand(NotchParser parser). The parser holds the Notch tokens after the command name, up to the end of the line. - Optionally parses a body in
parseBody(NotchTemplateParser parser), for a block bounded by a matching#end. - Writes its output in
render(NotchTemplateRuntime runtime, Drain out).
The engine makes a new instance of the command for each use in a template, so the class needs a public no-argument constructor.
import edu.montana.notch.NotchParser;
import edu.montana.notch.runtime.Drain;
import edu.montana.notch.templates.NotchTemplateCommand;
import edu.montana.notch.templates.NotchTemplateParser;
import edu.montana.notch.templates.ast.NotchTemplateContentBlock;
import edu.montana.notch.templates.command.EndCommand;
import edu.montana.notch.templates.runtime.NotchTemplateRuntime;
public class UpperCommand extends NotchTemplateCommand {
private NotchTemplateContentBlock body;
public UpperCommand() {
super("upper");
}
@Override
public void parseCommand(NotchParser parser) {
// #upper takes no arguments
}
@Override
public void parseBody(NotchTemplateParser parser) {
body = parser.parseContentBlock(new EndCommand());
addChildContent(body);
}
@Override
public void render(NotchTemplateRuntime runtime, Drain out) {
var sb = new StringBuilder();
body.render(runtime, new Drain(sb));
out.append(sb.toString().toUpperCase());
}
}
The built-in commands in the package edu.montana.notch.templates.command are good worked examples. BasicNotchTemplateCommands.java lists all 14.
Registration
NotchTemplates templates = new NotchTemplates();
BasicNotchTemplateCommands.addTo(templates);
templates.addCommand(new UpperCommand());
addCommand throws IllegalArgumentException if a command with the same name is already registered.
Templates can then use the new command:
#upper
hello ${ name }
#end
With name set to "ada" this renders HELLO ADA.
See also
- Built-in Commands for the 14 shipped commands; useful as a worked example.
- Overview for where commands fit in the broader engine.