0.0.2 • Published 6 years ago

koa-pug-render v0.0.2

Weekly downloads
1
License
MIT
Repository
github
Last release
6 years ago

koa-pug-render

npm install koa-pug-render

Koa middleware that defines ctx.render() on the Koa context for rendering Pug HTML templates.

const path = require('path')
const pugRender = require('koa-pug-render')

app.use(pugRender(path.join(__dirname, 'views')))

app.use(async ctx => {
    // Loads template "./views/homepage.pug"
    await ctx.render('homepage', {
        foo: 42,
        name: 'john'
     })
})

Usage

Here are the default options:

const pugRender = require('koa-pug-render')

app.use(pugRender({
    locals: {},
    ext: '.pug',
    cache: process.env.NODE_ENV === 'production',
    method: 'render',
}))

Options:

  • locals: These locals will be exposed to all templates. Templates can override them.
  • ext: If you render a template without an extension, this extension is used. Ex: ctx.render('hello') will look for hello.pug.
  • method: The name of the function this library will define on the Koa context.

Any other options are passed directly to Pug.

Pug Peculiarities

Pug has made some bizarre API decisions that affect this library.

Pug's renderFile() is synchronous

This library's render() is asynchronous, managing its own cache of template source strings and ensuring that parallel requests for the same template await the same promise.

Pug conflates template locals and render options

pug.renderFile('hello.pug', { debug: true }) passes debug into the hello.pug template. But the debug key is also one of Pug's options, so it also turns debug output on for this render.

This means it's possible to accidentally/silently override Pug options with keys that were only intended for the template.

This library protects against this by throwing an error if you try to use one of Pug's "reserved" options keys in your template locals.

Ideally Pug's API would separate these two different intentions into two different arguments: pug.renderFile(template, locals, options)