tdumitrescu / virtual-jade

Compile Jade templates to Hyperscript for Virtual DOM libraries
Other
31 stars 4 forks source link
hyperscript jade pug snabbdom virtual-dom

virtual-jade

NPM version Build status Test coverage

Compile your jade templates into Virtual DOM functions. Works with multiple Virtual DOM libraries, including:

For people who like declarative reactive templating, but don't like writing HTML or JSX.

Create a template:

.items
  each item in items
    .item(
      class={active: item.active}
      data-id=item.id
    )
      .item-title= item.title
      .item-description= item.description

require() your template as a function and use a rendering system like main-loop:

const mainLoop = require('main-loop');

const template = require('./items.jade');

const initState = {
  items: [],
};

const loop = mainLoop(initState, template, {
    create: require("virtual-dom/create-element"),
    diff: require("virtual-dom/diff"),
    patch: require("virtual-dom/patch"),
});
document.body.appendChild(loop.target);

Then update whenever you'd like!

loop.update({
  items: [
    {
      id: 'asdf',
      title: 'some title',
      description: 'some description',
      active: false,
    },
  ],
});

Notes

API

fnStr = render(str, options)

str is the jade source as a string. fnStr is output JS that you should include as a CommonJS module.

Options are:

Returns a string that looks like:

function render(locals) {
  var result_of_with = /* stuff */
  if (result_of_with) return result_of_with.value;;
}

You are expected to eval() the string if you want the source as a function. Otherwise, just create a module in the following format:

const js = `module.exports = ${fnStr}`;

Within code blocks in your template code, you can access Jade mixin functions via the $mixins variable. In virtual-jade, mixins boil down to functions that take arguments and return a tree of h(name, attrs, children). They are like React stateless components. Accessing them via $mixins is useful for special cases where you want to pass around handles to blocks of Jade code as callback functions (see example below).

mixin item(x)
  .item
    .more-tree= x + 1

list-virtual-scroll(props={itemRenderer: $mixins.item})
// in list-virtual-scroll.jade
each val in allItems.slice(startIdx, endIdx)
  = props.itemRenderer(val)

Development notes