Render

Print out your views and templates as response, i.e. you can use modules:

// register extension
Grown.use(require('@grown/render'));

fixture`./views/default.js
  module.exports = (data, h) =>
    h('html', null, h('body', null, data.contents));
`;

fixture`./views/Home/index.js
  module.exports = (_, h) => h('h1', null, 'It works!');
`;

fixture`./views/About/about.js
  module.exports = () => '<h1>About...</h1>';
`;

fixture`./views/Errors/not_found.js
  module.exports = () => '<h1>404</h1>';
`;

fixture`./views/example.pug
  h1 OSOM
`;

// setup middleware...
server.plug(Grown.Render({
  default_layout: 'default',
  view_folders: [
    __dirname + '/views',
  ],
}));

server.mount(async ctx => {
  // you can append/prepend to the head and body tags
  ctx.append('head', () => `<title>URL: ${ctx.req.url}</title>`);
  ctx.append('head', () => '<style>*{margin:0}</style>');

  // calls to render() will halt and emit before_render
  if (ctx.req.url === '/') return ctx.render('Home/index');
  if (ctx.req.url === '/about') return ctx.render('About/about');

  // calls to template() must be done asynchronously
  if (ctx.req.url === '/osom') {
    const result = await ctx.template('example.pug');

    // calls to partial() will return strings
    const chunk = ctx.partial('Home/index');

    return ctx.res.end(result + chunk);
  }

  return ctx.render('Errors/not_found');
});

Click ▷ RUN above and then try these links (Home, About, Example and Not found) below.


Views

Methods mixin

  • render(src[, data])
  • partial(src[, data])
  • template(src[, data])

Public props static

  • view_folders

Public methods static

  • render(src[, data])
  • partial(src[, data])
  • template(src[, data])
  • $install(ctx, scope)
  • $mixins()

Private* props static

  • _cache

Private* methods static

  • _buildPartial(view, data)
  • _buildvNode(tag, data)
  • _buildHTML(vnode, depth, context)
  • _buildAttr(key, value)
  • _buildCSS(style)
  • _partial(view, cached, options)
  • _render(fn, data)

Layout

Props mixin

  • chunks

Methods mixin

  • prepend(to, opts)
  • append(to, opts)

Public props static

  • default_layout

Public methods static

  • $before_render
  • $install()
  • $mixins()

Private* methods static

  • _renderSlot(opts, state)

Actions

Public methods static

  • $install(ctx)