Text Templates in PureScript

PureScript offers built-in support for creating dynamic content or showing customized output to the user with the Text.Formatting.Template module. This module provides a simple string templating system.

module Main where

import Prelude

import Data.Maybe (Maybe(..))
import Effect (Effect)
import Effect.Console (log)
import Text.Formatting.Template (formatTemplate)

main :: Effect Unit
main = do
  -- We can create a new template string.
  -- Templates are a mix of static text and "actions" enclosed in
  -- ${...} that are used to dynamically insert content.
  let t1 = "Value is ${value}\n"

  -- By "executing" the template we generate its text with
  -- specific values for its actions. The ${value} action is
  -- replaced by the value provided in the record.
  log $ formatTemplate t1 { value: "some text" }
  log $ formatTemplate t1 { value: 5 }
  log $ formatTemplate t1 { value: ["PureScript", "Haskell", "Elm", "F#"] }

  -- If the data is a record we can use the ${fieldName} action to access
  -- its fields.
  let t2 = "Name: ${name}\n"

  log $ formatTemplate t2 { name: "Jane Doe" }

  -- The same applies to records; there is no restriction on the
  -- case of key names.
  log $ formatTemplate t2 { name: "Mickey Mouse" }

  -- PureScript doesn't have built-in conditional templating,
  -- but we can achieve similar results using helper functions
  let condTemplate value = 
        if value == "" 
        then "no\n" 
        else "yes\n"

  log $ condTemplate "not empty"
  log $ condTemplate ""

  -- For iteration, we can use array functions like `map` and `join`
  let t4 = "Range: " <> (joinWith " " ["PureScript", "Haskell", "Elm", "F#"]) <> "\n"
  log t4

To run the program, save it as Main.purs and use the PureScript compiler (psc) to compile it, then run it with Node.js:

$ psc Main.purs -o output.js
$ node -e "require('./output').main()"
Value is some text
Value is 5
Value is ["PureScript","Haskell","Elm","F#"]
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: PureScript Haskell Elm F#

This example demonstrates basic string templating in PureScript. While PureScript doesn’t have a direct equivalent to Go’s text/template package, we can achieve similar functionality using the Text.Formatting.Template module and custom functions.

Note that PureScript’s type system and functional nature lead to some differences in how we approach templating compared to Go. For instance, we use record types instead of structs, and we handle conditionals and loops using functions rather than special template syntax.