Plain Thymeleaf
Thymeleaf
is an HTML (and more) template engine for Java. This is the core in action with nothing else.
You can find the complete code for this here: only-thymeleaf.
All of this is just putting into a project what has being posted in this stackoverflow answer which in turn was found on this comment on github.
We begin by getting only the core jar for Thymeleaf (the latest one at the time this post was written).
Then we create our template
inside resources on a directory apptly named templates
.
src/main/resources/templates/index.html
Inside the span tag
we have th
which is how all data attributes starts on Thymeleaf, you can see that it’s declared as a namespace definition above on the html tag. We are also using a variable expression ${}
with an Elvis operator ?:
which is an special operator that only returns it’s value when the evaluated expression returns null, which means if first_name
is null then (no first name specified)
will be returned.
Now to bring it all together: src/main/java/dev/jsedano/examples/onlythymeleaf/Main.java
Since we are not using Spring or nothing to helps us with dependency injection we will create objects the traditional way, setting up the prefix for where the templates will be stored and the suffix for them.
This will be the context which will hold the objects that Thymeleaf will use to generate the html.
Here we create a TemplateEngine
object and pass the resolver
, then we call process
on the templateEngine
object with the name of the template and the context we created above.
We can create our fat jar running mvn verify
and then call it with java -jar ./target/only-thymeleaf-1.0-jar-with-dependencies.jar
to print the result of the template processing, if we send variables when we executed we can see how they get replace:
For more information on Thymeleaf you can go directly to the thymeleaf docs.
Download the complete code for this here: only-thymeleaf.