JSON Template for Racket (and Typed Racket)
1 Installation
JSON Template for Racket is published as a PLaneT module. Simply (require (planet mbenkard/json-template/json-template)) to get started.
2 Usage
2.1 API
(make-template template-data) → procedure? |
template-data : string? |
The returned procedure expects a single argument, the subtitution context, and returns the expanded template as a string. Three types of contexts are supported:
Primitive contexts. These may be of any form whatever (valid primitive contexts are lists, numbers, symbols, strings, etc.) and are not treated specially. Their only purpose is being printed into the template expansion as plain text. Note that a primitive context does not make a whole lot of sense when used as an argument to "make-template" (although it can be used as such and referenced as "@"); it is much more commonly encountered as a nested context in a map.
Sequences. At present, these may only be lists. They can be iterated over by the use of repeated sections.
Maps. These may be any kinds of <dict?> objects; in particular, association lists and hash tables are fine choices. They can be indexed into by substitutions.
make-template’s behavior can be customized by the parameters formatters, meta-left, meta-right, default-formatter, and format-char.
For general information about JSON Template, see http://json-template.googlecode.com/svn/trunk/doc/Introducing-JSON-Template.html and http://code.google.com/p/json-template/wiki/Reference.
2.2 Examples
> (define template (make-template "\r\n<h1>{title|html}</h1>\r\n{.section people}\r\n<ul>\r\n{.repeated section @}\r\n <li>{name} ({age} years)</li>\r\n{.end}\r\n</ul>\r\n{.or}\r\n<p>No one's registered.</p>\r\n{.end}\r\n"))
> (template '((title . "<Registered People>") (people ((name . "Nathalie") (age . 24)) ((name . "Heinrich") (age . 28)) ((name . "Hans") (age . 25)))))
<h1><Registered People></h1>
<ul>
<li>Nathalie (24 years)</li>
<li>Heinrich (28 years)</li>
<li>Hans (25 years)</li>
</ul>
> (template '((title . "<Registered People>") (people)))
<h1><Registered People></h1>
<ul>
</ul>
> (template '((title . "<Registered People>")))
<h1><Registered People></h1>
<p>No one's registered.</p>