Step #3: Adding Some Handlebars

To generate HTML, it is often convenient to use a template language. There are lots of those, with a popular one being Handlebars. While the original Handlebars is in JavaScript, there is a port to Java, which we can use in our app. So, we will use it to pour our to-do item data into an HTML template to generate a Web page.

To that end, add this line to the dependencies closure in the app/build.gradle file:

  implementation "com.github.jknack:handlebars:4.1.2"

Then, in ToDoApp, add this single to our koinModule:

    single {
      Handlebars().apply {
        registerHelper("dateFormat", Helper<Instant> { value, _ ->
          DateUtils.getRelativeDateTimeString(
            androidContext(),
            value.toEpochMilli(),
            DateUtils.MINUTE_IN_MILLIS,
            DateUtils.WEEK_IN_MILLIS, 0
          )
        })
      }
    }

This creates a Handlebars singleton that Koin can inject into various places in our app. We configure the Handlebars object as part of setting it up, calling a registerHelper() function. This registers a “helper”, which we can refer to from templates to perform a bit of formatting work for us. Specifically, we are registering a dateFormat helper that takes an Instant object and formats it using DateUtils, as we are doing in our DisplayFragment.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.