Getting started
With Maven:
<dependency>
<groupId>au.com.codeka</groupId>
<artifactId>carrot</artifactId>
<version>2.4.5/version>
</dependency>
With Gradle:
compile 'au.com.codeka:carrot:2.4.5'
First, you need to create a CarrotEngine
, which will hold the environment for parsing templates and
processing them. The CarrotEngine
class is immutable, and you construct it by passing in a
Configuration
:
CarrotEngine engine = new CarrotEngine(new Configuration.Builder()
.setResourceLocator(new FileResourceLocator("path/to/templates"))
.build());
Typically, you'll have a "skeleton" template and a "body" template, where the skeleton defines the overall HTML structure that all your pages share, and the body template is the custom things just for that page. The way you do this is by having your body template extend the skeleton template, like so:
skeleton.html:
<!DOCTYPE html>
<html>
<head>
<title>{% block "title" %}{% end %}</title>
</head>
<body>
{% block "content" %}{% end %}
</body>
</html>
index.html:
{% extends "skeleton.html" %}
{% block "title" %}Hello World{% end %}
{% block "content" %}
<h1>Hello, World!</h1>
{% end %}
Finally to process a template, you use the process method:
Bindings bindings = new EmptyBindings();
System.out.println(engine.process("index.html", bindings));