Text Templates in GDScript

extends Node

func _ready():
    # We can create a new template and parse its body from
    # a string.
    # Templates are a mix of static text and "actions" enclosed in
    # {{...}} that are used to dynamically insert content.
    var t1 = Template.new()
    t1.parse("Value is {{.}}\n")

    # By "executing" the template we generate its text with
    # specific values for its actions. The {{.}} action is
    # replaced by the value passed as a parameter to execute().
    print(t1.execute("some text"))
    print(t1.execute(5))
    print(t1.execute(["GDScript", "Python", "C#", "C++"]))

    # Helper function we'll use below.
    func create(name: String, t: String) -> Template:
        var template = Template.new()
        template.parse(t)
        return template

    # If the data is a dictionary we can use the {{.key}} action to access
    # its values.
    var t2 = create("t2", "Name: {{.Name}}\n")

    print(t2.execute({"Name": "Jane Doe"}))

    # if/else provide conditional execution for templates. A value is considered
    # false if it's null, an empty string, 0, or an empty array.
    # This sample demonstrates another feature of templates: using - in actions
    # to trim whitespace.
    var t3 = create("t3", "{{if . -}} yes {{else -}} no {{end}}\n")
    print(t3.execute("not empty"))
    print(t3.execute(""))

    # for loops let us iterate through arrays or dictionaries. Inside
    # the loop block {{.}} is set to the current item of the iteration.
    var t4 = create("t4", "Range: {{for . }}{{.}} {{end}}\n")
    print(t4.execute(["GDScript", "Python", "C#", "C++"]))

# Custom Template class to mimic Go's text/template functionality
class Template:
    var template: String

    func parse(t: String) -> void:
        template = t

    func execute(data) -> String:
        var result = template

        if typeof(data) == TYPE_ARRAY:
            result = result.replace("{{for . }}", "").replace("{{end}}", "")
            var items = ""
            for item in data:
                items += str(item) + " "
            result = result.replace("{{.}}", items.strip_edges())
        elif typeof(data) == TYPE_DICTIONARY:
            for key in data:
                result = result.replace("{{." + key + "}}", str(data[key]))
        else:
            if data:
                result = result.replace("{{if . -}}", "").replace("{{else -}} no {{end}}", "")
            else:
                result = result.replace("{{if . -}} yes {{else -}}", "").replace("{{end}}", "")
            result = result.replace("{{.}}", str(data))

        return result

This GDScript code demonstrates how to create and use text templates, similar to Go’s text/template package. Here’s a breakdown of the main concepts:

  1. We create a custom Template class to mimic Go’s template functionality.

  2. Templates are created using the Template.new() method and parsed using the parse() method.

  3. The execute() method is used to generate text with specific values for the template’s actions.

  4. We use {{.}} as a placeholder for values in the template, similar to Go.

  5. Conditional statements (if/else) and loops (for) are implemented in a simplified manner.

  6. The code demonstrates working with different data types: strings, numbers, arrays, and dictionaries.

Note that GDScript doesn’t have built-in template functionality like Go, so we’ve created a basic implementation. This example provides a similar interface and functionality, but it’s not as feature-rich or efficient as Go’s text/template package.

To run this code, you would typically create a new Godot project, attach this script to a Node, and then run the project. The output would be similar to the Go example, printed to Godot’s output panel.