Handlebars - the next generation
Language specification

The Abstract Syntax Tree

The Abstract Syntax Tree of a Handlebars is a tree of JSON objects. Every node in the tree has at least the following properties:

  • type: Defines the node’s class and implies which additional properties are present on the node,
  • loc: Contains the location of the node in the template
    • start: The start of the node in the template
    • end: The end of the node in the template

Like in JavaScripts “splice” method, the end location is exclusive (i.e. the first character after the node.)

start and end consist of

  • line: The line number of the character (first line is 1)
  • column: The column of the charachter (fist columne is 0)

02-abstract-syntax-tree/empty.hb-spec.json
An empty template yields an empty result
Template:
Warning: The original Handlebars implementation has a deviating AST (which the author of this document considers to be wrong):
Input / Output
Input
{}
Output
AST
{
  "type": "Program",
  "body": [],
  "strip": {},
  "loc": {
    "start": { "line": 1, "column": 0 },
    "end": { "line": 1, "column": 1 }
  }
}
Original AST
{ "type": "Program", "body": [], "strip": {} }

02-abstract-syntax-tree/newline.hb-spec.json
A single newline
Template:

Input / Output
Input
{}
Output

AST
{
  "type": "Program",
  "body": [
    {
      "type": "ContentStatement",
      "value": "\n",
      "original": "\n",
      "loc": {
        "start": { "line": 1, "column": 0 },
        "end": { "line": 2, "column": 0 }
      }
    }
  ],
  "strip": {},
  "loc": {
    "start": { "line": 1, "column": 0 },
    "end": { "line": 2, "column": 0 }
  }
}

02-abstract-syntax-tree/newline-around-mustache.hb-spec.json
Newlines around a mustache statement
Template:

{{a}}
Input / Output
Input
{ "a": 2 }
Output

2
AST
{
  "type": "Program",
  "body": [
    {
      "type": "ContentStatement",
      "value": "\n",
      "original": "\n",
      "loc": {
        "start": { "line": 1, "column": 0 },
        "end": { "line": 2, "column": 0 }
      }
    },
    {
      "type": "MustacheStatement",
      "escaped": true,
      "params": [],
      "path": {
        "type": "PathExpression",
        "original": "a",
        "data": false,
        "depth": 0,
        "parts": ["a"],
        "loc": {
          "start": { "line": 2, "column": 2 },
          "end": { "line": 2, "column": 3 }
        }
      },
      "strip": { "open": false, "close": false },
      "loc": {
        "start": { "line": 2, "column": 0 },
        "end": { "line": 2, "column": 5 }
      }
    },
    {
      "type": "ContentStatement",
      "value": "\n",
      "original": "\n",
      "loc": {
        "start": { "line": 2, "column": 5 },
        "end": { "line": 3, "column": 0 }
      }
    }
  ],
  "strip": {},
  "loc": {
    "start": { "line": 1, "column": 0 },
    "end": { "line": 3, "column": 0 }
  }
}