koa-views-handlebars

0.1.1 • Public • Published

koa-views-handlebars

Handlebars template engine middleware for koa@2 based on koa-views.

Installation

npm install koa-views-handlebars --save

Templating engines

koa-views-handlebars is using koa-views under the hood, but provide easy way to config helpers and partails of handlebars.

NOTE: you must install the koa-views and handlebars before use this middleware, add them to your package.json dependencies.

npm install koa-views handlebars --save

Example

const hbs = require('koa-views-handlebars');
 
// setup middleware before router
app.use(hbs(__dirname , {
    helperDirs: __dirname + '/helpers',
    partialDirs: __dirname + '/views'
}));
 
app.use(async function (ctx) {
  await ctx.render('index', {
    title: 'Index Page'
  });
});

For more examples you can take a look at the tests.

API

hbs(rootPath, options)

  • rootPath: Where your views are located. Must be an absolute path. All rendered views are relative to this path
  • options (optional)

Very simple example.

app.use(hbs(__dirname))
  • options.extension: handelbars template file extension, default is hbs.

In this example, each file ending with .html will get rendered using the handlebars templating engine.

app.use(hbs(__dirname, { extension: 'html' }))
  • options.helperDirs: where your handlebars helpers are located, can be string (one dir) or array (multiple dirs).
// helpers in one dir
app.use(hbs(__dirname , {
    helperDirs: __dirname + '/helpers'
}));
 
// helpers in multiple dirs
app.use(hbs(__dirname , {
    helperDirs:[ __dirname + '/helpers1',  __dirname + '/helpers2']
}));
 
  • options.partialDirs: where your handlebars partials are located, can be string (one dir) or array (multiple dirs).
// partials in one dir
app.use(hbs(__dirname , {
    partialDirs: __dirname + '/views'
}));
 
// partials in multiple dirs (related path)
app.use(hbs(__dirname , {
    partialDirs:[ './views/layout',  './views/includes',  './views/pages']
}));
 
  • options.debug: set to true will print final options passed to koa-views
app.use(hbs(__dirname , {
    debug: true
}));
 

License

MIT

/koa-views-handlebars/

    Package Sidebar

    Install

    npm i koa-views-handlebars

    Weekly Downloads

    5

    Version

    0.1.1

    License

    MIT

    Unpacked Size

    12 kB

    Total Files

    12

    Last publish

    Collaborators

    • bruceman