hyperviews
hyperviews
is a template language that transforms to hyperscript h(tagName, attrs, children)
.
Use it as a build tool with any h(tag, props, children)
compliant framework e.g. React, preact or hyperapp.
const hv = // => h('div', { id: 'foo' }, (state.name))
Installation
npm i hyperviews
API
hyperviews(tmpl, mode, name, argstr)
tmpl
(required) - The template string.mode
- The output format. Can be one of [raw
,esm
,cjs
,browser
], or if any other value is passed the function is exported as a variable with that name. The default israw
.name
- The default output function name. The default isview
.args
- The default function arguments. The default isprops state
.
CLI
Reads the template from stdin,
cat examples/test.html | hyperviews --mode esm --name foo --args bar > examples/test.js
Template language
Interpolation
Use curly braces in attributes and text.
My name is {state.name} my age is {state.age} and I live at {state.address}
See more interpolation examples
Conditionals
There are two forms of conditional.
Using an if
attribute.
Show Me!
Or using tags <if>
, <elseif>
and <else>
1 2 bar is neither 1 or 2, it's {state.bar}!
if
tags can be nested.
Iteration
The each
attribute can be used to repeat over items in an Array.
Three additional variables are available during each iteration: $value
, $index
and $target
.
It supports keyed elements as shown here.
{post.title} {$index}
produces
Events
{state.foo}
produces this output
Style
The style
attribute expects an object
produces this output
Literal
The script
tag literally outputs it's contents.
This is also useful for recursive nodes, e.g. a tree
{state.name} {state.name}
produces this output
{ return { if statechildren return else return }}
Function
The function
tag outputs a function, returning it's contents.
Supports name
and args
attributes.
{x}
produces this output
{ return }
Components
Components are declared with if the tag starts with a capital letter.
produces this output
Module example
How you structure your app is down to you. I like to keep js and html in separate files so a component might look like this:
- MyComponent
- view.html (The template file e.g.
<div>{state.name}</div>
) - view.html.js (The transformed
h
output of the file above) - index.js (Imports the transformed view and exports the component)
- view.html (The template file e.g.
but if you want you could build entire modules in a html file like this:
Compiles to
{ superprops thisrender = view this { e // ... } } { return }
More examples here
Using browserify
?
Then install the hyperviewify
transform so you can simply require templates.
const view = require('./my-view.html')
npm i hyperviewify