Dropwizard - with Freemarker template

I wanted to produce a quick Dropwizard app, which would allow me to play with Freemarker templates.

A simple search, rendered as an HTML page, allowing some ideas to be tried out.

I’m not sure what you are up to when you stumble over this web page, but it’s closish to Christmas, and I am always busy at this time of year. There is always code to write, things to finish, and customers to keep motivated, happy, and open.

This is important, as a career programmer.

Moving on to Dropwizard…..

You will find all the code in the following Git repo:

https://github.com/chocksaway/dropwizardTemplateSearch

I have taken the basic Dropwizard application from http://dropwizard.io/en/stable/getting-started.html, up to Running our App

Dropwizard Views with Freemarker templates

Start off by taking a look at https://www.dropwizard.io/en/stable/manual/views.html

Start off by looking at SearchView.java:

package com.chocksaway;

import io.dropwizard.views.View;

/**
 * Author milesd on 15/12/2019.
 */
public class SearchView extends View {
    private final Saying search;

    protected SearchView(Saying search) {
        super("Search.ftl");
        this.search = search;
    }

    public Saying getSearch() {
        return search;
    }
}

I am referencing Search.ftl, which is the ‘freemarker template’.

There is a reference to the SearchView at the top of the file.

<#-- @ftlvariable name="" type="com.chocksaway.SearchView" -->

The rest of the Search.ftl template is an HTML web page. There is a Freemarker templating language (refer to https://freemarker.apache.org/docs/dgui_datamodel_basics.html for the basics).

You can reference Java, pojo values directly from the view:

<h2>Hello, ${search.getContent()}!</h2>

You can also declare variables within the template, call a freemarker function, and return a matching list:

<#function filter data name value>
    <#local result = []>
    <#list data as each>
        <#if each[name] == value>
            <#local result = result + [each]>
        </#if>
    </#list>
    <#return result>
</#function>

<#-- some test data -->
<#assign data = [ {"propertyName":"my value",    "foo":100},
{"propertyName":"other value", "foo":101},
{"propertyName":"my value",    "foo":102}] >

<#assign filteredData = filter(data, "propertyName", "my value") >

<#list filteredData as item>
    ${item.foo}
</#list>

A typical Dropwizard application will query a database, and pass the results back to the view, which will display the data, using an ftl template.