For Gauche 0.9.6

Next: , Previous: , Up: Library modules - Utilities   [Contents][Index]

12.57 text.template - Simple template expander

Module: text.template

This module lifts Gauche’s built-in string interpolation feature to be more general template engine.

Gauche’s string interpolation syntax is expanded at read time and then handled by macro expanders, and becomes a simple Scheme code fragment. For example, if you have this:

(let ([x 10])
  #"The square of x is ~(* x x).")

It is eventually converted to this after macro expansion:

(let ([x 10])
  (string-append '"The square of x is " (x->string (* x.0 x.0)) '"."))

It is a kind of template expansion, but you have to have the template string as a literal, so it’s restricted. With this module, you can feed template string and the bindings of the value at the runtime:

(define *template* "The square of x is ~(* x x).")

(expand-template-string *template*
  (make-template-environment :bindings '(x 10)))
  ⇒ "The square of x is 100."

The syntax of template strings is the same as string interpolation (see String interpolation); that is, tokens following ~ is read as a Scheme expression. In case if the token is a symbol and you need to delimit it from subsequent characters, you can use symbol escape by |.

You also need to provide a template environment, where the expressions in the template is evaluated. Note that, unlike string interpolation, those expressions can’t refer to the local bindings.

Function: expand-template-string template env

Expands a template string template with a template environment env, and returns the result string.

Function: expand-template-file filename env :optional paths

Reads a template string from a file named by filename, expands it with a template environment env, and returns the result string.

If filename is not an absolute path, it is looked in the directories listed in paths.

Function: make-template-environment :key extends imports bindings

Creates and returns a template environment. A template environment is like a module (see Modules): It maps symbols to values, and it can import bindings from other modules, or extend other modules.

The keyword arguments extends and imports must be a list of symbols; they specify names of modules to inherit from or to import from.

The keyword arguments bindings must either be a dictionary (anything that inherits <dictonary>), or a key-value list. The mappings represented by it are incorporated to the environment.

Next: , Previous: , Up: Library modules - Utilities   [Contents][Index]