Coder Social home page Coder Social logo

koa-views's Introduction

koa-views

Build status NPM version NPM downloads Dependency Status License

Template rendering middleware for koa.

Note: This master branch is for koa@2. Take a look at the v1.x branch for koa@1 (not supported).

Installation

npm install koa-views

Templating engines

koa-views is using consolidate under the hood.

List of supported engines

Example

var views = require('koa-views');

// Must be used before any router is used
app.use(views(__dirname + '/views', {
  map: {
    html: 'underscore'
  }
}));

app.use(async function (ctx, next) {
  ctx.state = {
    session: this.session,
    title: 'app'
  };

  await ctx.render('user', {
    user: 'John'
  });
});

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

Simple middleware

If you need to simply render pages with locals, you can install koa-views-render:

npm install koa-views-render

Then simply use it on your routes and its arguments will be passed to ctx.render.

var render = require('koa-views-render');

// ...

app.use(render('home', { title 'Home Page' });

API

views(root, opts)

  • root: Where your views are located. Must be an absolute path. All rendered views are relative to this path
  • opts (optional)
  • opts.extension: Default extension for your views

Instead of providing the full file extension you can omit it.

app.use(async function (ctx) {
  await ctx.render('user.pug')
})

vs.

app.use(views(__dirname, { extension: 'pug' }))

app.use(async function (ctx) {
  await ctx.render('user')
})
  • opts.map: Map a file extension to an engine

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

app.use(views(__dirname, { map: {html: 'nunjucks' }}))

// render `user.html` with nunjucks
app.use(async function (ctx) {
  await ctx.render('user.html')
})
  • opts.engineSource: replace consolidate as default engine source

If you’re not happy with consolidate or want more control over the engines, you can override it with this options. engineSource should be an object that maps an extension to a function that receives a path and options and returns a promise. In this example templates with the foo extension will always return bar.

app.use(views(__dirname, { engineSource: {foo: () => Promise.resolve('bar')}}))

app.use(async function (ctx) {
  await ctx.render('index.foo')
})
  • opts.options: These options will get passed to the view engine. This is the time to add partials and helpers etc.
const app = new Koa()
  .use(views(__dirname, {
    map: { hbs: 'handlebars' },
    options: {
      helpers: {
        uppercase: (str) => str.toUpperCase()
      },

      partials: {
        subTitle: './my-partial' // requires ./my-partial.hbs
      }
    }
  }))
  .use(function (ctx) {
    ctx.state = { title: 'my title', author: 'queckezz' }
    return ctx.render('./my-view.hbs')
  })

Debug

Set the DEBUG environment variable to koa-views when starting your server.

$ DEBUG=koa-views

License

MIT

koa-views's People

Contributors

amalininhere avatar avindra avatar cuteboi avatar damianb avatar helloyou2012 avatar i5ting avatar ifraixedes avatar int64ago avatar kmohrf avatar marcusoftnet avatar merty avatar naxmefy avatar niftylettuce avatar nimthenerd avatar queckezz avatar tangdaohai avatar theverything avatar thomasdezeeuw avatar vendethiel avatar wsmpanda avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.