I am working on a small quarkus project serving HTML pages created with the qute templating engine.
I was wondering if it possible to access some String constant values to the template, without having to pass them as .data("key", value)
to the template.
One example, I have defined constants for my query parameters, and I would like to use them in the HTML I am producing with the template engine.
Adapted from the official guide Qute is a templating engine
My JAX-RS class /src/main/java/com/company/HelloResource.java
looks like this:
package com.company
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateInstance;
@Path("hello.html")
public class HelloResource {
@Inject
Template hello;
private static final String NAME_QUERY_PARAM = "name";
@GET
@Produces(MediaType.TEXT_HTML)
public TemplateInstance get(@QueryParam(NAME_QUERY_PARAM) String name) {
String helloStatement;
if (name == null) {
helloStatement = "Welcome!";
} else {
helloStatement = "Hello " + name + "!";
}
return hello.data("helloStatement", helloStatement);
}
}
And the hello template /src/main/resources/templates/hello.html
looks like this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body>
<h1>{helloStatement}</h1>
<form action="./hello.html" method="GET">
<div>
<label for="name">The name:</label>
<input name="name" id="name" value="John">
</div>
<div>
<button>Say hi!</button>
</div>
</form>
</body>
</html>
For the <input>
tag I would like to write:
<input name="{com.company.HelloResource.NAME_QUERY_PARAM}" id="name" value="John">
And having com.company.HelloResource.NAME_QUERY_PARAM
replaced with its value at compile time.
As indicated by Martin Kouba a way to solve this is to use the TemplateData
annotation:
package com.company;
import io.quarkus.qute.TemplateData;
@TemplateData
public class Constants {
public static final String NAME_QUERY_PARAM = "name";
}
And use it like this:
<input name="{com_company_Constants:NAME_QUERY_PARAM}" id="name" value="John">