Sample Courses
Notice the "search" view has a few course hard coded into it. Let's change this so courses data are passed to it dynamically.
Drop this code snippet inside the WebServer.main
:
List<Course> courses = new ArrayList<>();
courses.add(new Course("EN.500.112","GATEWAY COMPUTING: JAVA"));
courses.add(new Course("EN.601.220","INTERMEDIATE PROGRAMMING"));
courses.add(new Course("EN.601.226","DATA STRUCTURES"));
courses.add(new Course("EN.601.229","COMPUTER SYSTEM FUNDAMENTALS"));
courses.add(new Course("EN.601.231","AUTOMATA and COMPUTATION THEORY"));
Then update the following route method:
get("/search", (req, res) -> {
return new ModelAndView(null, "search.hbs");
}, new HandlebarsTemplateEngine());
to
get("/search", (req, res) -> {
Map<String, Object> model = Map.of("courses", courses);
return new ModelAndView(model, "search.hbs");
}, new HandlebarsTemplateEngine());
We are using the model
object to pass courses
object to Handlebars template engine.
The power of handlebars is in that it can parse the Java object it receives.
Open search.hbs
and replace the following segment:
<ul class="course-list">
<li class="course-list-item">EN.601.226 Data Structures</li>
<li class="course-list-item">EN.601.280 Full-Stack JavaScript</li>
<li class="course-list-item">EN.601.421 Object-Oriented Software Engineering</li>
</ul>
with this segment:
<ul class="course-list">
{{#each courses}}
<li class="course-list-item">{{offeringName}} {{title}}</li>
{{/each}}
</ul>
Note the use of {{ }}
as part of the handlebars templating engine. Handlebars has several constructs; the one we've used above is the #each
construct to iterate over a collection. Handlebars receives courses
object and it knows it is an Iterable
Java collection. Inside the #each
block, you have access to each element of courses
(i.e. each Course
object). Moreover, handlebars knows Course
is a POJO, so when you write {{offeringName}}
, handlebars understands you are looking for the property (field) called offeringName
and it uses the getter methods of Course
to retrieve it (i.e. getOfferingName()
).
Run the application. Visit http://localhost:4567/search. Notice the courses data displayed are those we created in the WebServer.main
and not hard coded into the search.hbs
any more.