Thursday, April 09, 2009

Introducing JSON Template

Introducing JSON Template

JSON Template is a minimal but powerful templating language, currently implemented in both Python and JavaScript.

To use it, simply copy the Python file or the JavaScript file into your project. Neither has any external dependencies.

Since there are over one bajillion template languages for Python alone, it deserves some explanation. But first here are some examples.

Simple example

>>> import jsontemplate
>>> jsontemplate.expand('Hello {name}', {'name': 'world'})
'Hello world'

This Python example should look familiar to many people.* The JavaScript version is a straightforward translation of this API.


Thus, there's a very simple programming pattern for "Web 2.0" sites:

  1. Create a JSON structure in response to an HTTP request.
  2. If say ?format=json is in the URL, then output the raw JSON.
  3. If not, combine the JSON with a Template string and output an HTML page (or Atom feed, etc.).

In this way, JSON Template is the complement of JSON. When you use a template language to express program logic, this one-to-one correspondence between human-consumable data and machine-consumable data is hard to achieve.

The language is deliberately small, and it is declarative rather than procedural.


More Features

  • Comes with a default set of "formatters", so it's easy to get escaping/security right.
  • Extensible with your own application-specific formatters
  • A small degree of customizable syntax makes it appropriate for many problem domains (not just web programming).
  • Fast and hackable implementation. Tokenization, parsing, compilation, and template expansion are all cleanly separated in the code. (Like many template languages, instantiating a jsontemplate.Template object compiles the template string, and it can be subsequently re-expanded with different data dictionaries without parsing.)