Thymeleaf
Ratpack provides modules that support the Thymeleaf template engine.
build.gradle
dependencies {
compile "io.ratpack:ratpack-thymeleaf:${ratpack}"
}
Add a module.
Function<Registry, Registry> registry = ratpack.guice.Guice.registry( bindings -> {
bindings.module( new ThymeleafModule() );
} );
By default, the Thymeleaf module recognizes * .html
files under $ {BaseDir} / thymeleaf
as templates. Therefore, it is necessary to set BaseDir
.
ServerConfig.builder()
.development( true )
.findBaseDir( "public/.ratpack" )
In this case, public / thymeleaf
is considered the template directory.
The module registers a Renderer
for the ratpack.thymeleaf.Template
class. Note that it is not a renderer ** for Thymeleaf's ʻIContext**.
Template can be created from the
Template.thymeleafTemplate () `method.
Action<Chain> handlers = chain -> {
chain.get( "/:name?", ctx -> {
String name = ctx.getPathTokens().get( "name" );
name = name.isEmpty() ? "world" : name;
ctx.render( Template.thymeleafTemplate( ImmutableMap.of( "name", name ), "template" ) );
} );
};
The map of the first argument is the parameter binding and the second argument is the name of the template. If BaseDir
is public / .ratpack
, the actual file to be resolved will be public / thymeleaf / template.html
.
The template file is exactly the same as a regular Thymeleaf.
template.html
<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html; charset=UTF-8" />
</head>
<body>
<h1 th:text="'hello, ' + ${name}"></h1>
</body>
</html>
As you can see, using Thymeleaf is very easy. The module implementation itself is easy to create, as long as you have a class that represents the template and an implementation of the renderer that wraps the template engine. I think it would be easy to support Velocity and other template engines with a similar pattern.
~~ The modules provided by the Ratpack official are currently (February 2018) up to Thymeleaf 2.1.5. It doesn't support version 3 (I implemented it myself because it can't be helped-Promotion). ~~ Officially supported in 1.6.0 and later. Please use that.
Recommended Posts