Thymeleaf
Since Camel 4.1
Only producer is supported
The Thymeleaf component allows you to process a message using a Thymeleaf template. This can be very powerful when using Templating to generate responses for requests.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-thymeleaf</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI format
thymeleaf:templateName[?options]
Where templateName is the name of the template, which the template resolver (the resolver option) turns into the template: a resource on the classpath by default.
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Thymeleaf component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Whether the template gets the whole Exchange in its context. The template always gets body, header, headers, variable, variables and exception; with true it also gets exchange, in and request (the message), out and response (the message, for InOut), exchangeProperty, exchangeProperties and camelContext. Use request rather than in, as in is a keyword of the OGNL expressions of Thymeleaf. This gives the template the full CamelContext API, which is a security risk when the template is not trusted. This is the default for all endpoints of the component. | false | boolean | |
Whether the CamelThymeleafResourceUri and CamelThymeleafTemplate headers can replace the template of the endpoint. CamelThymeleafResourceUri gives another resource URI, which Camel renders with an endpoint of the same options; CamelThymeleafTemplate is passed to the template engine as the template, read as template text by the STRING and DEFAULT resolvers and as a template name by the others. Camel removes both headers. Enable it only when the message senders are trusted, as whoever sets these headers chooses the template that runs. This is the default for all endpoints of the component. | false | boolean | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean |
Endpoint Options
The Thymeleaf endpoint is configured using URI syntax:
thymeleaf:resourceUri
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required Path to the resource. You can prefix with: classpath, file, http, ref, or bean. classpath, file and http loads the resource using these protocols (classpath is default). ref will lookup the resource in the registry. bean will call a method on a bean to be used as the resource. For bean you can specify the method name after dot, eg bean:myBean.myMethod. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Sets whether the context map should allow access to all details. By default only the message body and headers can be accessed. This option can be enabled for full access to the current Exchange and CamelContext. Doing so impose a potential security risk as this opens access to the full power of CamelContext API. | false | boolean | |
Whether the CamelThymeleafResourceUri and CamelThymeleafTemplate headers can replace the template of the endpoint. CamelThymeleafResourceUri gives another resource URI, which Camel renders with an endpoint of the same options; CamelThymeleafTemplate is passed to the template engine as the template, read as template text by the STRING and DEFAULT resolvers and as a template name by the others. Camel removes both headers. Enable it only when the message senders are trusted, as whoever sets these headers chooses the template that runs. | false | boolean | |
Whether the template engine caches the resolved and parsed template. When not set, the Thymeleaf default applies: true for the CLASS_LOADER, FILE, URL and WEB_APP resolvers, false for STRING. Set it to false to read a changed template again on every message. The DEFAULT resolver always caches. | Boolean | ||
How long, in milliseconds, a cached template stays valid in the template cache of the template engine before it is resolved and parsed again. Only used when the template is cacheable. When not set, a cached template stays until the template cache (200 entries) evicts it as the least recently used one. Not used by the DEFAULT resolver. | Long | ||
Whether the template resolver checks that the template resource exists before it returns it. A missing template then fails with a template resolution error instead of an error when the template is read. Thymeleaf defaults to false. Not passed to the URL resolver, and the STRING and DEFAULT resolvers always find their template. | Boolean | ||
The Thymeleaf template mode: HTML, XML, TEXT, JAVASCRIPT, CSS, or RAW (outputs the template as it is, without processing). With the CLASS_LOADER, FILE, URL and WEB_APP resolvers, a resource name (with prefix and suffix) that ends with a known file extension sets the template mode and this option is ignored: .html, .htm and .xhtml for HTML; .xml, .rss and .atom for XML; .js and .json for JAVASCRIPT; .css for CSS; .txt for TEXT. An unknown value falls back to HTML. Enum values:
| HTML | String | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
The character encoding, such as UTF-8, that the template resolver reads the template resource with. When not set, the JVM default charset is used. Used by the CLASS_LOADER, FILE, URL and WEB_APP resolvers; a template that Camel loads itself (resource URI with a scheme) is always read with the JVM default charset. | String | ||
The order of the template resolver in the resolver chain of the template engine. The endpoint configures only one template resolver, so the order has no effect. | Integer | ||
The prefix that the template resolver adds to the template name to build the resource name, such as templates/. Used by the CLASS_LOADER, FILE, URL and WEB_APP resolvers. | String | ||
The Thymeleaf template resolver that turns the template name into the template: CLASS_LOADER (ClassLoaderTemplateResolver) reads a resource from the classpath, FILE (FileTemplateResolver) reads a file, relative to the working directory or absolute, URL (UrlTemplateResolver) reads the template name as a URL, STRING (StringTemplateResolver) uses the template name itself as the template text, DEFAULT (DefaultTemplateResolver) uses the template of the first message for all messages, as the template engine is created on the first message, and WEB_APP (WebApplicationTemplateResolver) reads a resource of a Jakarta Servlet web application, which needs a JakartaServletWebApplication set on the endpoint in Java. When the resource URI has a scheme such as classpath:, file: or ref: and the resolver is not URL, Camel loads the template text itself and passes the text as the template name, which only STRING and DEFAULT can use. Enum values:
| CLASS_LOADER | ThymeleafResolverType | |
The suffix that the template resolver adds to the template name to build the resource name, such as .html. It is not added when the template name already ends with a known file extension (.html, .htm, .xhtml, .xml, .rss, .atom, .js, .json, .css, .txt). Used by the CLASS_LOADER, FILE, URL and WEB_APP resolvers. | String |
Message Headers
The Thymeleaf component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelThymeleafResourceUri (producer) Constant: | A resource URI to render instead of the one of the endpoint. Camel gets an endpoint with this resource URI and the same options, and removes the header. Only read when allowTemplateFromHeader is true. | String | |
CamelThymeleafTemplate (producer) Constant: | The template to render instead of the resource of the endpoint, passed to the template engine as the template: the template text with the STRING and DEFAULT resolvers, a template name with the other resolvers. Camel removes the header. Only read when allowTemplateFromHeader is true. | String | |
CamelThymeleafVariableMap (producer) Constant: | A Map of extra variables for the template context. Camel adds its own entries (body, header, headers, variable, variables, exception and, with allowContextMapAll, the Exchange entries) to this Map, so they replace keys of the same name. Read even when allowTemplateFromHeader is false; Camel removes the header after use. | Map | |
CamelThymeleafServletContext (producer) Constant: | Deprecated The ServletContext for a web application. Deprecation note: Never read by the component: the web application template resolver is built from the JakartaServletWebApplication given to ThymeleafEndpoint.setJakartaServletWebApplication, which is not a URI option. | ServletContext |
Message Body
The message body at each side of the Thymeleaf component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Producer input |
| The template gets the body as ${body}, as it is: text, or a Map, a List or a POJO to read from; no body prints as empty text, and bytes or a stream are not read as text. The template is the resource, or the CamelThymeleafTemplate header with allowTemplateFromHeader=true, never the body. |
Producer output |
| The text the template writes, in its templateMode such as HTML. The headers are kept. |
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Headers set during the Thymeleaf evaluation stay on the message, thus making it possible to return values from Thymeleaf to the Message.
For example, to set the header value of fruit in the Thymeleaf template fruit-template.html, on an endpoint with allowContextMapAll=true:
[(${request.setHeader('fruit', 'Apple')})] The fruit header is now on the message after the Thymeleaf endpoint.
Usage
Thymeleaf Context
Camel will provide exchange information in the Thymeleaf context (just a Map). The Exchange is transferred as: The body, header, headers, variable, variables and exception entries are always there; the others only when the endpoint has allowContextMapAll=true.
| key | value |
|---|---|
| The |
| The |
| The headers of the In message. |
| The Camel Context instance. |
| The In message. |
| The In message ( |
| The In message body. |
| The Out message (only for InOut message exchange pattern). |
| The Out message (only for InOut message exchange pattern). |
You can add your own variables to the Thymeleaf context with a Map in the message header CamelThymeleafVariableMap. Camel sets the body, header, headers, variable, variables and exception entries on top of it, and removes the header after use:
Map<String, Object> variableMap = new HashMap<>();
variableMap.put("greeting", "Hello");
exchange.getIn().setHeader("CamelThymeleafVariableMap", variableMap); Hot reloading
Thymeleaf caches the template by default (cacheable is true for the CLASS_LOADER, FILE, URL and WEB_APP resolvers), so the template is only loaded once, and thus hot reloading is not possible. This scenario can be used in production when the resource never changes. If you set cacheable=false, the template is read again on every message, which makes it hot reloadable for both file and classpath resources (expanded jar).
Dynamic templates
Camel provides two headers by which you can define a different resource location for a template or the template content itself. If any of these headers is set, and the endpoint has allowTemplateFromHeader=true, then Camel uses this over the endpoint configured resource. This allows you to provide a dynamic template at runtime.
| Header | Type | Description |
|---|---|---|
|
| A URI for the template resource to use instead of the endpoint configured. |
|
| The template to use instead of the endpoint configured. With the |
Examples
For a simple use case, you could use something like:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("thymeleaf:com/acme/MyResponse.html"); <route>
<from uri="activemq:My.Queue"/>
<to uri="thymeleaf:com/acme/MyResponse.html"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: thymeleaf:com/acme/MyResponse.html To use a Thymeleaf template to formulate a response to a message for InOut message exchanges (where there is a JMSReplyTo header).
If you want to use InOnly and consume the message and send it to another destination, you could use the following route:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("thymeleaf:com/acme/MyResponse.html")
.to("activemq:Another.Queue"); <route>
<from uri="activemq:My.Queue"/>
<to uri="thymeleaf:com/acme/MyResponse.html"/>
<to uri="activemq:Another.Queue"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: thymeleaf:com/acme/MyResponse.html
- to:
uri: activemq:Another.Queue And to use the content cache, e.g., for use in production, where the .html template never changes:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("thymeleaf:com/acme/MyResponse.html?cacheable=true")
.to("activemq:Another.Queue"); <route>
<from uri="activemq:My.Queue"/>
<to uri="thymeleaf:com/acme/MyResponse.html?cacheable=true"/>
<to uri="activemq:Another.Queue"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: thymeleaf:com/acme/MyResponse.html
parameters:
cacheable: true
- to:
uri: activemq:Another.Queue And a file-based resource:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("thymeleaf:myfolder/MyResponse.html?resolver=FILE&cacheable=true")
.to("activemq:Another.Queue"); <route>
<from uri="activemq:My.Queue"/>
<to uri="thymeleaf:myfolder/MyResponse.html?resolver=FILE&cacheable=true"/>
<to uri="activemq:Another.Queue"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: thymeleaf:myfolder/MyResponse.html
parameters:
resolver: FILE
cacheable: true
- to:
uri: activemq:Another.Queue It’s possible to specify what template the component should use dynamically via a header, so for example:
-
Java
-
XML
-
YAML
from("direct:in")
.setHeader("CamelThymeleafResourceUri").constant("path/to/my/template.html")
.to("thymeleaf:dummy?allowTemplateFromHeader=true"); <route>
<from uri="direct:in"/>
<setHeader name="CamelThymeleafResourceUri">
<constant>path/to/my/template.html</constant>
</setHeader>
<to uri="thymeleaf:dummy?allowTemplateFromHeader=true"/>
</route> - route:
from:
uri: direct:in
steps:
- setHeader:
name: CamelThymeleafResourceUri
expression:
constant:
expression: path/to/my/template.html
- to:
uri: thymeleaf:dummy
parameters:
allowTemplateFromHeader: true It’s possible to specify a template directly as a header. The component should use it dynamically via a header, with the STRING resolver (the other resolvers read the header as a template name), so, for example:
-
Java
-
XML
-
YAML
from("direct:in")
.setHeader("CamelThymeleafTemplate").constant("Hi this is a thymeleaf template that can do templating [(${body})]")
.to("thymeleaf:dummy?allowTemplateFromHeader=true&resolver=STRING"); <route>
<from uri="direct:in"/>
<setHeader name="CamelThymeleafTemplate">
<constant>Hi this is a thymeleaf template that can do templating [(${body})]</constant>
</setHeader>
<to uri="thymeleaf:dummy?allowTemplateFromHeader=true&resolver=STRING"/>
</route> - route:
from:
uri: direct:in
steps:
- setHeader:
name: CamelThymeleafTemplate
expression:
constant:
expression: "Hi this is a thymeleaf template that can do templating [(${body})]"
- to:
uri: thymeleaf:dummy
parameters:
allowTemplateFromHeader: true
resolver: STRING The Email Example
In this sample, we want to use Thymeleaf templating for an order confirmation email. The email template is laid out in Thymeleaf as:
Dear [(${headers.lastName})], [(${headers.firstName})]
Thanks for the order of [(${headers.item})].
Regards Camel Riders Bookstore
[(${body})] And the java code (from a unit test):
private Exchange createLetter() {
Exchange exchange = context.getEndpoint("direct:a").createExchange();
Message msg = exchange.getIn();
msg.setHeader("firstName", "Claus");
msg.setHeader("lastName", "Ibsen");
msg.setHeader("item", "Camel in Action");
msg.setBody("PS: Next beer is on me, James");
return exchange;
}
@Test
public void testThymeleafLetter() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.message(0).body(String.class).contains("Thanks for the order of Camel in Action");
template.send("direct:a", createLetter());
mock.assertIsSatisfied();
}
from("direct:a")
.to("thymeleaf:org/apache/camel/component/thymeleaf/letter.txt")
.to("mock:result");