1 | 'use strict'
|
2 |
|
3 | const { resolve } = require('path')
|
4 | const debug = require('debug')('koa-views')
|
5 | const consolidate = require('consolidate')
|
6 | const send = require('koa-send')
|
7 | const getPaths = require('get-paths')
|
8 | const pretty = require('pretty')
|
9 |
|
10 | module.exports = viewsMiddleware
|
11 |
|
12 | function 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 |
|
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 |
|
44 |
|
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 |
|
59 | function isHtml(ext) {
|
60 | return ext === 'html'
|
61 | }
|