Thymeleaf Extras
- Thymeleaf extra modules for customizing templates
- Note: This project is unofficial and experimental.
TOC
thymeleaf-extras-minify
Example
- Thymeleaf template
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <!-- head --> <head> <meta charset="utf-8" /> <title th:text="bar">foo</title> <style> body { font-size: 1rem; } </style> ......
- Processed HTML
<!DOCTYPE html><html><head><meta charset="utf-8" /><title>bar</title><style>body { font-size: 1rem; }</style>......
Usage
-
Add a dependency in your project.
<dependency> <groupId>com.github.spt-oss</groupId> <artifactId>thymeleaf-extras-minify</artifactId> <version>3.0.11.0</version> </dependency>
-
Add the
MinifierDialect
to theTemplateEngine
instance.import org.thymeleaf.TemplateEngine; import org.thymeleaf.extras.minify.dialect.MinifierDialect; TemplateEngine engine = new TemplateEngine(); engine.addDialect(new MinifierDialect());
-
Or setup Spring configurations if your project is based on Spring Boot.
spring.thymeleaf: prefix: classpath:/templates/
import org.springframework.context.annotation.Bean; import org.thymeleaf.extras.minify.dialect.MinifierDialect; @Bean public MinifierDialect minifierDialect() { return new MinifierDialect(); }
Customization
-
Create a subclass of AbstractMinifierTemplateHandler or SimpleMinifierTemplateHandler.
package my.project; import org.thymeleaf.extras.minify.engine.AbstractMinifierTemplateHandler; public class MyMinifierTemplateHandler extends AbstractMinifierTemplateHandler { ...... }
-
Set the class to the first argument of the
MinifierDialect
. Note that only class type is accepted because of Thymeleaf processor's restriction.import my.project.MyMinifierTemplateHandler; TemplateEngine engine = new TemplateEngine(); engine.addDialect(new MinifierDialect(MyMinifierTemplateHandler.class));
import my.project.MyMinifierTemplateHandler; @Bean public MinifierDialect minifierDialect() { return new MinifierDialect(MyMinifierTemplateHandler.class); }
References
- https://stackoverflow.com/questions/39098106/how-to-minify-thymeleaf-generated-html
- The answer is very helpful.
License
- This software is released under the Apache License 2.0.