Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Brendan Whiting
Front End Web Development Techdegree Graduate 84,692 PointsWhy does every route create its own new HandlebarsTemplateEngine()?
Why not just have one engine that they all reference?
package com.teamtreehouse.courses;
import com.teamtreehouse.courses.model.CourseIdeaDAO;
import com.teamtreehouse.courses.model.SimpleCourseIdeaDAO;
import spark.ModelAndView;
import spark.template.handlebars.HandlebarsTemplateEngine;
import java.util.HashMap;
import java.util.Map;
import static spark.Spark.get;
import static spark.Spark.post;
import static spark.Spark.staticFileLocation;
/**
* Created by brendan.whiting on 12/12/16.
*/
public class Main {
public static void main(String[] args) {
staticFileLocation("/public");
CourseIdeaDAO dao = new SimpleCourseIdeaDAO();
get("/", (req, res) -> {
Map<String, String> model = new HashMap<>();
model.put("username", req.cookie("username"));
return new ModelAndView(model, "index.hbs");
}, new HandlebarsTemplateEngine());
post("/sign-in", (req, res) -> {
Map<String, String> model = new HashMap<>();
String username = req.queryParams("username");
res.cookie("username", username);
model.put("username", username);
return new ModelAndView(model, "sign-in.hbs");
}, new HandlebarsTemplateEngine());
get("/ideas", (req, res) -> {
Map<String, Object> model = new HashMap<>();
model.put("ideas", dao.findAll());
return new ModelAndView(model, "ideas.hbs");
}, new HandlebarsTemplateEngine());
}
}

Donatas Zilenas
8,384 PointsSame also...
2 Answers

Sławomir Lasik
7,792 PointsI am guessing that in this situation, where the Spark framework calls the get/post route methods asynchronously, meaning, that call may take some time. And if you pass the same HandlebarsTemplateEngine object it can stuck in executing. Like in threads with some kind of locks.

Doli Harahap
6,246 PointsBut somehow, the documentation said it will be removed in the future: http://sparkjava.com/documentation#views-and-templates
"There are two main ways of rendering a template in Spark. You can either call render directly in a standard route declaration (recommended), or you can provide the template-engine as a third-route parameter (likely to be removed in the future):"
Gyorgy Andorka
13,811 PointsGyorgy Andorka
13,811 PointsI was wondering the same thing.