Skip to content

Templates

Module templates

This port provides a common interface for rendering templates with multiple different template engines.

Install the Dependency

This module is not meant to be used directly. You should include any Adapter implementing this feature (as templates_pebble and/or templates_freemarker) in order to process templates.

You can use many adapters in the same application to be able to handle different template engines at the same time.

Register a Template Engine

You can register multiple template engines using regular expressions:

1
2
3
4
5
TemplateManager.adapters = mapOf(
    Regex(".*\\.html") to SampleTemplateAdapter("html"),
    Regex(".*\\.txt") to SampleTemplateAdapter("text"),
    Regex(".*") to SampleTemplateAdapter("others"),
)

The template adapter is selected from top to bottom, picking the first matched one.

You can use Glob syntax to bind patterns to template adapters if you prefer:

1
2
3
4
5
TemplateManager.adapters = mapOf(
    Glob("*.html").regex to SampleTemplateAdapter("html"),
    Glob("*.txt").regex to SampleTemplateAdapter("text"),
    Glob("*").regex to SampleTemplateAdapter("others"),
)

Usage

To render a template, you have to use the TemplateManager object. The data to be used inside the template must be supplied in a map (context), the template URL and current time-stamp (_template_ and _now_ variables) are added to the context automatically. Check the code below for an example:

1
2
val context = mapOf("key1" to "value1", "key2" to "value2")
val rendered = TemplateManager.render(urlOf("classpath:template.txt"), context)

Package com.hexagonkt.templates

Feature implementation code.