Spring+Freemarker Tips

I hope you will find following tips useful when developing Spring Boot application with Freemarker.

  1. Enable auto-reload of freemarker templates

    • Create spring boot development profile (e.g. “local”)

    • Disable template caching and enable file access rather than classpath resource access to templates (application-local.properties).

      properties
      1spring.freemarker.cache=false
      2spring.freemarker.prefer-file-system-access=true
      3spring.freemarker.template-loader-path=file:${user.home}/projects/example/src/main/resources/templates
  2. Add src/main/resources/freemarker_implicit.ftl to declare your most commonly used types (freemarker_implicit.ftl):

    freemarker
    1[#ftl]
    2[#-- @implicitly included --]
    3[#-- @ftlvariable name="items" type="java.util.List<com.example.domain.Item>" --]
  3. Set setting url_escaping_charset to avoid specifying it in templates (application-local.properties):

    properties
    1spring.freemarker.settings.url_escaping_charset=UTF-8
  4. You may want to import your default layout to all your pages automatically (application.properties)

    properties
    1spring.freemarker.settings.auto_import=layout/defaultLayout.ftl as layout

    This is equivalent to adding explicitly to your page:

    freemarker
    1<#import "../layout/defaultLayout.ftl" as layouts>

Why Freemarker and not a Thymeleaf? Because Thymeleaf is one of the slowest template engines for Java. Freemarker is in the middle of the list, 1.5 times faster than Thymeleaf. Velocity or JMustache are even faster, but the difference is not as big and Freemarker has quite a lot of useful features.

Konstantin Pavlov

Konstantin Pavlov

Software Engineer working with Java, Kotlin, Swift, and AI. Focusing on software architecture and building AI-infused apps. Passionate about testing and Open-Source projects.