Bambang pramusintha

Archive for the ‘JSON’ Category

Knowing JSON Template

In JavaScript, JSON, Python, Themplate on September 16, 2012 at 12:26 pm

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.

Full Example

To read this example, keep in mind the following:

  • A variable can be substituted by surrounding its name with curly braces: {}
  • Template “directives” start with a period: .
  • In place of for loops and if statements, the basic idea is that the template declares sections and repeated sections. The sections are named after keys in the JSON data dictionary. The presence or absence of the keys in the JSON dictionary implicitly determines if and how many times a section is expanded.
  • If a JSON dictionary key is missing or empty ([], {}, or null), then the {.or} section is expanded.

These few constructs are surprisingly powerful.

The following example uses most of the language, but not all. Read the rest of this entry »

%d bloggers like this: