hyperscript

Create HyperText with Nim.


Keywords
hyperscript, templating, nim-lang
License
MIT
Install
nimble install hyperscript

Documentation

hyperscript

A functional Nim library for combining DOM pieces, with compile-time superpowers. hyperscript creates composable HTML and SVG with Nim, both client- and server-side:

import hyperscript

let example =
  h("div#page",
    h("div#header",
      h("h1.classy", "h", { style: {"background-color": "#22f"} })),
    h("div#menu", { style: {"background-color": "#2f2"} },
      h("ul",
        h("li", "one"),
        h("li", "two"),
        h("li", "three"))),
      h("h2", "content title",  { style: {"background-color": "#f22"} }),
      h("p",
        "so it's just like a templating engine,\n",
        "but easy to use inline with Nim\n"),
      h("p",
        "the intention is for this to be used to create\n",
        "reusable, interactive HTML widgets. "))

(Currently, only literal arguments are supported, but this limitation will be removed in a future release, see #8 and #10.)

Installation

hyperscript works with Nim 1.2.6+ and can be installed using Nimble:

$ nimble install hyperscript

How does it work?

The basic design consists of compiling down to efficient calls to the DOM (through the dom standard library). As such, the following,

let example = h("p#example",
  h("input.name[value=Name]",
    style: {"background": "yellow"},
  ),
)

compiles roughly to

let example =
  let node = document.createElement("p")
  for attr in items([("id", "example")]):
    node.setAttribute(attr[0], attr[1])
  for child in items([
    let node = document.createElement("input")
    for attr in items([("value", "Name"), ("class", "name"), ("style", "background: yellow;")]):
      node.setAttribute(attr[0], attr[1])
    node]):
    node.appendChild(child)
  node

(We intend to unroll all loops in the future, see #6.)

When not compiling to JavaScript, XmlNode objects are generated using the xmltree standard library. Using the C backend, for instance, the example above compiles to

let example =
  newXmlTree("p", [
      newXmlTree("input", @[],
        {"value": "Name", "class": "name", "style": "background: yellow;"}.toXmlAttributes,
      ),
    ], {"id": "example"}.toXmlAttributes,
  )

Some references

Convert HTML snippets to hyperscript: