1. Background

We will create an HTML file that have some dynamic content using thymeleaf as the template engine. To see more about thymeleaf click here. The assumption is you have a little background with Java and maven.

What you will need?
1. JDK 1.8
2. At least Maven 3
3. IDE is optional but I use eclipse in this project.

2. Directory Structure

The directory structure will be as follows.

maven-structure

2. The pom.xml

We will use maven and spring boot to get the required libraries for this tutorial. Discussion for maven and spring boot are out of scope for this tutorial. Please see pom.xml below:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>jgal-tutorials</groupId>
	<artifactId>jgal-filewriter-thymeleaf</artifactId>
	<version>0.1.0</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.5.RELEASE</version>
	</parent>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>nz.net.ultraq.thymeleaf</groupId>
			<artifactId>thymeleaf-layout-dialect</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>spring-releases</id>
			<url>https://repo.spring.io/libs-release</url>
		</repository>
	</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>spring-releases</id>
			<url>https://repo.spring.io/libs-release</url>
		</pluginRepository>
	</pluginRepositories>
</project>

4. The Thymeleaf config

The creation of a configuration file for thymeleaf is only done once so we will create a singleton class. We will create a class named ThymeLeafConfig under the package com.jgal.filewriter.thymeleaf. The method named getTemplateEngine will return the engine that will be use to process the templates and data. Initialization of the template engine object is done automatically in the constructor.

package com.jgal.filewriter.thymeleaf;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.FileTemplateResolver;

public enum ThymeLeafConfig {
	INSTANCE;
	private TemplateEngine templateEngine;
	
	private ThymeLeafConfig(){
		FileTemplateResolver templateResolver = new FileTemplateResolver();
		templateResolver.setPrefix(getTemplatePath());
		templateResolver.setTemplateMode("HTML5");
		templateEngine = new TemplateEngine();
		templateEngine.setTemplateResolver(templateResolver);
	}
	
	private String getTemplatePath(){
		return ThymeLeafConfig.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "templates/";
	}
	
	public static TemplateEngine getTemplateEngine(){
		return INSTANCE.templateEngine;
	}
}

5. Template file

We will create a file named hello.html under the templates directory. Please see the directory structure above. Unlike freemarker and apache velocity, thymeleaf have a different approach for its template.

<!DOCTYPE html>
<html>
	<head>
		<title th:text="${title}">title</title>
	</head>
	<body>
	Hello <span th:text="${name}">name</span>! 
	</body>
</html>

6. The Application Runner

We will create a class named Application which will run and generate a file from a template file with supplied values to some variables. This is basically just simple class with a main method and a run method. In the run method, we will do the following:

1. Create a Context object containing string key value pair.
2. Create a Writer object which will be the output file.
3. We process the Context object and template file and get the string value.
4. The string value wil be supplied to the Writer object.
5. We flush and close our Writer object.

package com.jgal.filewriter.thymeleaf;

import java.io.FileWriter;
import java.io.Writer;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.thymeleaf.context.Context;

@SpringBootApplication
public class Application implements CommandLineRunner{

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
	
	public void run(String... arg0) throws Exception {
		Context context = new Context();
		context.setVariable("title", "User Page");
		context.setVariable("name", "John Doe");
		
		Writer writer = new FileWriter("C:/output/hello-thymeleaf.html");
		writer.write(ThymeLeafConfig.getTemplateEngine().process("hello.html", context));
		writer.close();
		
	}

}


7. Finally we run the code!

Under the directory where the pom.xml is located run mvn spring-boot:run in the command line. You can check the output file and compare it from the template file to see the differences.

8. Conclusion

We were able to generate an HTML file using thymeleaf as the template engine.