Spark and Freemarker
Spark doesn't provide a template engine solution. Like I said in a previous post, Spark is simple and customizable, so integrate a template engine is quick easy.
Why a template engine ?
For a clean code and to avoid duplicated code! Template engine brings layout hierarchy possibilities. In my opinion, it's an essential feature which provides clear html pages.
I chose Freemarker but I could use another one, Velocity for instance.
How to integrate Freemarker in Spark application?
Add Freemarker library to your project adding it in the buildpath or adding a new dependency in your pom.xml whether you work with Maven.
I put my template files in a "templates" directory placed in my root directory project.
myproject |_src |_templates |_main.ftl |_pages |_home.ftl |_...
main.ftl is my main template, it looks like this:
<!DOCTYPE html> <html> <head> <title>${title}</title> </head> <body> <#include page /> </body> </html>
And here is my home page template, home.ftl:
<h1>Welcome to my site!</h1> <p>This is the home page!</p>
My code looks like this:
public class Application { public static void main(String[] args) throws IOException { final Configuration cfg = configureFreemarker(); get(new Route("/") { @Override public Object handle(Request request, Response response) { //freemarker needs a Writer to render the final Html code StringWriter sw = new StringWriter(); //params used in the template files //passed the sublayout filename and the title page HashMap params = getPageParams("home.ftl", "Home page"); try { //template engine processing cfg.getTemplate("main.ftl").process(params, sw); } catch (Exception e) { e.printStackTrace(); } //return the rendered html code return sw.toString(); } }); } private static Configuration configureFreemarker() { Configuration cfg = new Configuration(); try { //indicates the templates directory to freemarker cfg.setDirectoryForTemplateLoading(new File("templates")); } catch (IOException e) { e.printStackTrace(); } return cfg; } //uses to create a Hashmap with specific keys private static HashMap getPageParams(String page, String title) { HashMap params = new HashMap(); //page and title from main.ftl params.put("page", "pages/" + page); params.put("title", title); return params; } }
Easy, isn't it ?
Spark and Freemarker represent a really good combination of simplicity.
See Freemarker documentation for specific uses.












