UNPKG

1.76 kBJavaScriptView Raw
1'use strict'
2
3const { resolve } = require('path')
4const debug = require('debug')('koa-views')
5const consolidate = require('consolidate')
6const send = require('koa-send')
7const getPaths = require('get-paths')
8const pretty = require('pretty')
9
10module.exports = viewsMiddleware
11
12function viewsMiddleware(
13 path,
14 { engineSource = consolidate, extension = 'html', options = {}, map } = {}
15) {
16 return function views(ctx, next) {
17 if (ctx.render) return next()
18
19 ctx.render = function(relPath, locals = {}) {
20 return getPaths(path, relPath, extension).then(paths => {
21 const suffix = paths.ext
22 const state = Object.assign(locals, options, ctx.state || {})
23 // deep copy partials
24 state.partials = Object.assign({}, options.partials || {})
25 debug('render `%s` with %j', paths.rel, state)
26 ctx.type = 'text/html'
27
28 if (isHtml(suffix) && !map) {
29 return send(ctx, paths.rel, {
30 root: path
31 })
32 } else {
33 const engineName = map && map[suffix] ? map[suffix] : suffix
34
35 const render = engineSource[engineName]
36
37 if (!engineName || !render)
38 return Promise.reject(
39 new Error(`Engine not found for the ".${suffix}" file extension`)
40 )
41
42 return render(resolve(path, paths.rel), state).then(html => {
43 // since pug has deprecated `pretty` option
44 // we'll use the `pretty` package in the meanwhile
45 if (locals.pretty) {
46 debug('using `pretty` package to beautify HTML')
47 html = pretty(html)
48 }
49 ctx.body = html
50 })
51 }
52 })
53 }
54
55 return next()
56 }
57}
58
59function isHtml(ext) {
60 return ext === 'html'
61}