jtwig template engine in a Spring Boot application


Separating the business logic from the presentation layer can save you a lot of headache during project maintenance. Unless the frontend is managed with a framework like Angular or Vue.js you should use a template engine. Check out how to utilize jtwig in a Spring Boot project.

What we are going to build

There are many template engines compatible with Spring Boot, for me the easiest one to work with is jtwig. In this example I will show you how to:

Feel free to browse through the jtwig documentation, as it’s short but exhaustive.


Add jtwig to your project

Let’s add the jtwig dependency to the project in the pom.xml file. Copy the following code into the <dependencies> section:

If you are working in InteliJ IDE choose Enable Autoimport option when prompted or confirm this option in settings. The dependency is now included into the project.

Create views

We will create a simple landing page, just to test that the views are handled properly. Firstly, we need a base template that will be extended by other views. It contains a {% block %} called content, were all child templates can define their essence. We will also place here all built css as well as javascript assets that are available across the app:

Now we can create the landing page view with it’s own content – the page extends the base template and includes views for the app’s navigation and intro section. For this example I used a page from Material Design for Bootstrap theme – Minimalist Intro:

Create the file with the navigation:

Now create the file with the intro section:

Create a controller to display your landing page

As an example controller, I created LandingPageController.java with an action to display the new landing page:

Now you can rebuild your project and refresh the http://localhost:8080/ in the browser.

Our example, built according to the theme documentation, looks like this:


If you want to add a personal touch

This landing page is sufficient if you want to test your template engine implementation and assets management. However, as you can see, the menu requires some adjustments to work exactly like the one in the MDBoostrap example. You may also want to customize some styles. Check out the Custom css in a Spring Boot Project with gulp post to see how you can easily modify the look of your application.

Photo by Matheus Bertelli on StockSnap

One thought on “jtwig template engine in a Spring Boot application

Leave a Reply

Your email address will not be published. Required fields are marked *