|
| 1 | +@file:Suppress("PackageDirectoryMismatch") |
| 2 | + |
| 3 | +package playground.velocity |
| 4 | + |
| 5 | +import org.apache.velocity.Template |
| 6 | +import org.apache.velocity.VelocityContext |
| 7 | +import org.apache.velocity.app.VelocityEngine |
| 8 | +import playground.shouldBe |
| 9 | +import java.io.StringWriter |
| 10 | +import java.util.* |
| 11 | + |
| 12 | +/** |
| 13 | + * Velocity is a Java-based template engine. It permits anyone to use a simple yet powerful template language to reference objects defined in Java code. |
| 14 | + * |
| 15 | + * [Apache Velocity Engine - User Guide](https://velocity.apache.org/engine/2.3/user-guide.html) |
| 16 | + * [Apache Velocity Engine - Developer Guide](https://velocity.apache.org/engine/2.3/developer-guide.html) |
| 17 | + */ |
| 18 | +fun main() { |
| 19 | + println() |
| 20 | + println("# Velocity") |
| 21 | + |
| 22 | + val engine = velocityEngine() |
| 23 | + helloWorld(engine) |
| 24 | + complexExample(engine) |
| 25 | +} |
| 26 | + |
| 27 | + |
| 28 | +fun helloWorld(engine: VelocityEngine) { |
| 29 | + val context = VelocityContext() |
| 30 | + context.put("name", "Velocity") |
| 31 | + val template: Template = engine.getTemplate("hello.vm") |
| 32 | + template.apply(context) shouldBe """ |
| 33 | + <body> |
| 34 | + Hello Velocity World! |
| 35 | + </body> |
| 36 | + """.trimIndent() |
| 37 | + |
| 38 | +} |
| 39 | + |
| 40 | + |
| 41 | +fun complexExample(engine: VelocityEngine) { |
| 42 | + val context = VelocityContext().apply { |
| 43 | + put("name", "Velocity") |
| 44 | + put("details", true) |
| 45 | + put("customer", VelocityCustomer("Jean-Michel", 39)) |
| 46 | + put("groceries", listOf("apple", "milk")) |
| 47 | + } |
| 48 | + engine.getTemplate("complex.vm").apply(context) shouldBe """ |
| 49 | + Hello Velocity |
| 50 | + I speak French |
| 51 | + Customer Jean-Michel is 41 years old. |
| 52 | + Is he old? true enough |
| 53 | + Groceries: |
| 54 | + - apple |
| 55 | + - milk |
| 56 | + """.trimIndent() |
| 57 | +} |
| 58 | + |
| 59 | +data class VelocityCustomer(val name: String, var age: Int) { |
| 60 | + fun isOld() = age >= 40 |
| 61 | +} |
| 62 | + |
| 63 | + |
| 64 | +private fun Template.apply(context: VelocityContext) : String { |
| 65 | + val sw = StringWriter() |
| 66 | + merge(context, sw) |
| 67 | + return sw.toString().trim() |
| 68 | +} |
| 69 | + |
| 70 | +private fun velocityEngine(): VelocityEngine { |
| 71 | + val properties = Properties().also { |
| 72 | + it.setProperty( |
| 73 | + "resource.loader.file.path", |
| 74 | + "/Users/jmfayard/Documents/GitHub/kotlin-libraries-playground/kotlin-jvm/src/main/resources" |
| 75 | + ) |
| 76 | + } |
| 77 | + val engine = VelocityEngine(properties) |
| 78 | + engine.init(); |
| 79 | + return engine |
| 80 | +} |
0 commit comments