Handlebars

Handlebars is one of the most popular template engines that works with most programming languages, including Java.

Handlebars is based on another template language called {{ mustache }} (handlebars like a style of mustache; get it?). The latter is named mustache because if you look at a curly brace sideways, it kind of looks like mustaches (and the templating language makes extensive use of curly braces).

To use handlebars in Spark, you need to add the following to the dependencies clause of build.gradle:

implementation 'com.sparkjava:spark-template-mustache:2.7.1'
implementation 'com.sparkjava:spark-template-handlebars:2.7.1'

Then open the Gradle tool window and refresh the Gradle project.

Make a new folder inside src/resources and call it templates. Create a file index.hbs inside the templates folder with the following content:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JHU Course Search</title>
  </head>
  <body>
    <h1>Welcome to CourseSearch UI!</h1>
  </body>
</html>

IntelliJ has a plugin for handlebars-mustache that helps with editing the template files. I highly recommend installing it.

Next, update WebServer.java as follows:

import spark.ModelAndView;
import spark.template.handlebars.HandlebarsTemplateEngine;

import static spark.Spark.*;

public class WebServer {
  public static void main(String[] args) {
    get("/", (req, res) -> {
      return new ModelAndView(null, "index.hbs");
    }, new HandlebarsTemplateEngine());
  }
}

Run the application and visit http://localhost:4567/. The welcome message must be displayed exactly as before! However, under the hood, you are sending a complete HTML document to the client. Right click in your browser and select "View Page Source".