What kind of a solution is thymeleaf?

Niklas R. picture Niklas R. · Aug 6, 2016 · Viewed 16.1k times · Source

I read that thymeleaf is preferred instead of JSP nowadays. Which problem does thymeleaf solve that JSP can't? How is thymeleaf compared to other templating engines?

Answer

Miloš Milivojević picture Miloš Milivojević · Aug 25, 2016

Well, this is really an opinion-based question and such will be my answer :)

The main difference is that JSPs are compiled to Java servlet classes whereas Thymeleaf reads the template file, parses its DOM and then applies the model to it. This introduces a performance overhead and gives JSPs a performance edge, even with Thymeleaf's template caching enabled. On the other hand, it makes Thymeleaf much easier to develop with and here's why:

  • Thymeleaf uses plain HTML as its templates. You can either choose a pure HTML5 approach with data-th attributes or the original custom-namespace th: attributes. The benefit of using plain HTML is that you can open it in a browser, which makes it easier for the designers to do their work: both the designers and developers can work on the same file.

  • Thymeleaf templates can be used without an application server and they also work nicely with embedded servers. You don't have to jump through hoops to do integration testing of your templates, which you can do either through Thymeleaf's own standalone template testing library or as a part of functional tests, e.g. integration tests of your Spring MVC controllers.

  • Thymeleaf has more lightweight and more powerful syntax and better integration with Spring ecosystem. It was designed to integrate with Spring from its conception, but you can also use it outside of Spring. I found it useful for email and report generation.

  • Thymeleaf templates allow for great reuse; you can create small template fragments and reuse them in other templates, which is a lifesaver in projects with lots of templates. It also has great layout support out of the box although you can also find community plugins if you need more flexibility/power.

Disclaimer: I haven't done any Thymeleaf development in over a year but from what I can see, it hasn't changed that much. You can also take a look at this article from Spring - while it is a bit old, it does illustrate the main differences.