Text Templates in Scala

Scala offers built-in support for creating dynamic content or showing customized output to the user with the scala.util.parsing.combinator.RegexParsers package. While it doesn’t have a direct equivalent to Go’s text/template, we can achieve similar functionality using string interpolation and custom functions.

import scala.util.parsing.combinator._

object TextTemplates extends App {

  // We can create a new template by defining a function that takes a parameter
  // and returns a string with interpolated values.
  def t1(value: Any): String = s"Value is $value\n"

  // Using the template
  println(t1("some text"))
  println(t1(5))
  println(t1(List("Scala", "Java", "Kotlin", "Clojure")))

  // Helper function to create templates
  def create(template: String): Any => String = (value: Any) => template.replace("{{.}}", value.toString)

  // If the data is a case class we can use string interpolation to access its fields.
  case class Person(name: String)
  def t2(person: Person): String = s"Name: ${person.name}\n"

  println(t2(Person("Jane Doe")))

  // The same applies to maps
  val personMap = Map("Name" -> "Mickey Mouse")
  println(s"Name: ${personMap("Name")}\n")

  // Conditional execution can be achieved using if-else expressions
  def t3(value: Any): String = {
    if (value.toString.nonEmpty) "yes\n" else "no\n"
  }

  println(t3("not empty"))
  println(t3(""))

  // For looping through collections, we can use Scala's built-in collection methods
  def t4(items: Seq[String]): String = {
    s"Range: ${items.mkString(" ")}\n"
  }

  println(t4(Seq("Scala", "Java", "Kotlin", "Clojure")))
}

To run the program, save it as TextTemplates.scala and use scala:

$ scala TextTemplates.scala
Value is some text
Value is 5
Value is List(Scala, Java, Kotlin, Clojure)
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: Scala Java Kotlin Clojure

In this Scala version:

  1. We use string interpolation (s"...") to create simple templates.
  2. For more complex templates, we define functions that take parameters and return formatted strings.
  3. We use case classes and maps to demonstrate accessing fields or keys in templates.
  4. Conditional execution is achieved using if-else expressions.
  5. Looping through collections is done using Scala’s built-in collection methods like mkString.

While Scala doesn’t have a built-in templating engine like Go’s text/template, this approach provides similar functionality for simple use cases. For more complex templating needs, you might want to consider using a dedicated templating library like Scalate or Twirl.