node2html

Library for generating html from json.

MIT License

Stars
3

node2html

A library for generating HTML from js objects.

Features:

  1. No insignificant whitespace characters As all formatting collapses, but text literals are untouched

  2. Works as a template engine As you have a full programming language at your disposal

  3. Infinite expandability As this library knows nothing about what it generates

Example

This javascript object:

[
    'html',
    [
        '$DOCTYPE', 'a-html',
        'head',
        [
            'title', 'HELLO'
        ],
        'body',
        [
            'span', 'hello'
        ]
    ]
]

Becomes the following HTML markup:

<!DOCTYPE a-html>
<html>
    <head>
        <title>HELLO</title>
    </head>
    <body>
        <span>hello</span>
    </body>
</html>

Syntax

node2html uses array-based AST nodes:

[
    selector,
    value,

    ...
]

selector

Contains the tagname, id and the classname:

'tagName#tagId.class.class1.class2'

value

Contains tag's content and attributes. It is one of the following:

  • A string (if tag only contains text) ['span', 'hello']
  • An array, containing tag's content and attributes['span', [...]]

Setting attributes

Attributes are set using a $ prefix:

[
    'span',
    [
        '$rel', 'label'
    ]
]

Text literals

You can add text literals to markup, using $:

[
    'span',
    [
        'span.icon-home', [],
        '$', 'Go home',
        'span.icon-go', []
    ]
]

Unpacking

You can "unpack" tags from an array using $$:

var getSpanContent = function gsc()
{
    return [
                'span.icon-home', ['$', 'home'],
                'span.icon-go', ['$', 'go']
            ];
};

[
    'span',
    [
        '$$', getSpanContent()
    ]
]

Stream support

node2html also provides a blocking stream wraparound, for use with gulp etc.