Text Templates in Racket

Our program demonstrates the use of text templates in Racket. Racket provides built-in support for creating dynamic content or showing customized output to the user with the racket/format module.

#lang racket

(require racket/format)

(define (main)
  ; We can create a new template as a function that takes a value
  ; and formats it into a string.
  (define (t1 value)
    (~a "Value is " value "\n"))

  ; By "executing" the template we generate its text with
  ; specific values.
  (displayln (t1 "some text"))
  (displayln (t1 5))
  (displayln (t1 '("Racket" "Scheme" "Lisp" "Clojure")))

  ; Helper function we'll use below.
  (define (create-template format-string)
    (lambda (value) (~a format-string value "\n")))

  ; If the data is a hash table we can use the `hash-ref` function to access
  ; its fields.
  (define t2 (create-template "Name: "))

  (displayln (t2 (hash-ref #hash(("Name" . "Jane Doe")) "Name")))

  ; The same applies to association lists.
  (displayln (t2 (assoc-ref '(("Name" . "Mickey Mouse")) "Name")))

  ; Racket's `if` provides conditional execution.
  ; This sample demonstrates using `~a` for formatting.
  (define (t3 value)
    (~a (if (not (empty? value)) "yes" "no") "\n"))

  (displayln (t3 "not empty"))
  (displayln (t3 ""))

  ; `for` loops let us iterate through lists.
  (define (t4 lst)
    (~a "Range: " (string-join (map ~a lst) " ") "\n"))

  (displayln (t4 '("Racket" "Scheme" "Lisp" "Clojure"))))

(main)

To run the program, save it as templates.rkt and use the racket command:

$ racket templates.rkt
Value is some text
Value is 5
Value is (Racket Scheme Lisp Clojure)
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: Racket Scheme Lisp Clojure

In this Racket version, we’ve used functions to represent templates. The ~a function from racket/format is used for string formatting. We’ve also used Racket’s built-in data structures like hash tables and association lists to demonstrate similar functionality to Go’s structs and maps.

The if statement in Racket is used for conditional execution, and the for loop is replaced with map and string-join functions to iterate over lists.

While Racket doesn’t have a direct equivalent to Go’s text/template package, this example shows how to achieve similar functionality using Racket’s built-in features and the racket/format module.