Text Templates in Groovy

import groovy.text.SimpleTemplateEngine

def main() {
    // We can create a new template and parse its body from
    // a string.
    // Templates are a mix of static text and placeholders enclosed in
    // ${...} that are used to dynamically insert content.
    def engine = new SimpleTemplateEngine()
    def t1 = engine.createTemplate('Value is ${it}\n')

    // By "executing" the template we generate its text with
    // specific values for its placeholders. The ${it} placeholder is
    // replaced by the value passed as a parameter to make().
    println t1.make(it: 'some text')
    println t1.make(it: 5)
    println t1.make(it: ['Groovy', 'Java', 'Kotlin', 'Scala'])

    // If the data is a map we can use the ${fieldName} placeholder to access
    // its fields.
    def t2 = engine.createTemplate('Name: ${name}\n')

    println t2.make([name: 'Jane Doe'])

    // The same applies to objects; with objects there is no restriction on the
    // case of property names.
    println t2.make(new Person(name: 'Mickey Mouse'))

    // if/else provide conditional execution for templates. A value is considered
    // false if it's null, an empty string, or a boolean false.
    // This sample demonstrates another feature of Groovy templates:
    // using the ternary operator for concise conditional expressions.
    def t3 = engine.createTemplate('${it ? "yes" : "no"}\n')
    println t3.make(it: 'not empty')
    println t3.make(it: '')

    // Groovy's each method lets us loop through collections. Inside
    // the each block, 'it' is set to the current item of the iteration.
    def t4 = engine.createTemplate('Range: ${it.collect { "$it " }.join()}\n')
    println t4.make(it: ['Groovy', 'Java', 'Kotlin', 'Scala'])
}

class Person {
    String name
}

main()

This Groovy script demonstrates text templating, which is similar to Go’s text templates but uses Groovy’s built-in templating capabilities. Here’s a breakdown of the key differences and similarities:

  1. Groovy uses ${...} for placeholders instead of Go’s {{...}}.

  2. We use the SimpleTemplateEngine class to create and process templates.

  3. Instead of Execute, we use the make() method to render templates.

  4. Groovy’s templating is more flexible with data types. We can pass maps, objects, or use the implicit it variable.

  5. Conditional logic in Groovy templates can use the ternary operator for simpler if/else constructs.

  6. For loops in Groovy templates typically use the each method or other collection processing methods like collect.

  7. Groovy doesn’t require explicit type declarations, making the code more concise.

When you run this script, it will produce output similar to the original Go example, demonstrating various templating features in Groovy.

The script shows how to create templates, use placeholders, work with different data types, implement conditional logic, and iterate over collections, all using Groovy’s templating capabilities.