All Downloads are FREE. Search and download functionalities are using the official Maven repository.

.port_templates.1.3.7.source-code.TemplateEngine.kt Maven / Gradle / Ivy

There is a newer version: 1.4.7
Show newest version
package com.hexagonkt.templates

import com.hexagonkt.helpers.toDate
import com.hexagonkt.injection.InjectionManager
import com.hexagonkt.serialization.parse
import java.net.URL
import java.time.LocalDateTime
import java.util.Locale

/**
 * A TemplateEngine can be used to render templates
 */
class TemplateEngine(
    private val adapter: TemplatePort = InjectionManager.inject(),
    private val settings: TemplateEngineSettings = TemplateEngineSettings()
) {

    private var parametersCache: Map> = mapOf()

    constructor(settings: TemplateEngineSettings = TemplateEngineSettings()) : this(
        InjectionManager.inject(),
        settings
    )

    fun render(resource: String, locale: Locale, context: Map): String =
        adapter.render(resourcePath(resource), locale, context(resource, locale, context), settings)

    private fun resourcePath(resource: String) =
        settings.basePath?.let { "$it/$resource" } ?: resource

    fun render(resource: String, locale: Locale, vararg context: Pair): String =
        render(resource, locale, linkedMapOf(*context))

    private fun loadProps(path: String): Map =
        try {
            URL("classpath:${settings.basePath}/$path.yml").parse()
        }
        catch (e: Exception) {
            mapOf()
        }

    @Suppress("UNCHECKED_CAST")
    private fun loadBundle(path: String, locale: Locale): Map = loadProps(path).let {
        (it[locale.language] ?: if (it.isNotEmpty()) it.entries.first().value else it)
            as Map + (it["data"] ?: mapOf()) as Map
    }

    private fun context(resource: String, locale: Locale, context: Map): Map {
        val bundlePath = resource.substringBeforeLast('.')

        val key = locale.country + locale.language + bundlePath
        if (!parametersCache.containsKey(key)) {
            val commonBundle = loadBundle("common", locale)
            val templateBundle = loadBundle(bundlePath, locale)
            parametersCache = parametersCache + (key to commonBundle + templateBundle)
        }

        val parameters: Map = parametersCache[key] ?: emptyMap()

        val now = LocalDateTime.now().toDate()
        val defaultProperties = mapOf("_template_" to resource, "_now_" to now)
        return parameters + context + defaultProperties
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy