Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
68 lines (52 loc) · 1.42 KB
/
Copy pathindex.js
File metadata and controls
68 lines (52 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// ------------------------------------
// #KOA - POSTHTML
// ------------------------------------
'use strict'
const fs = require('co-fs')
const path = require('path')
const copy = require('copy-to')
const posthtml = require('posthtml')
const defaults = {
ext: 'html',
options: {sync: true},
plugins: [],
writeResp: true
}
exports = module.exports = function (app, settings) {
if (app.context.render) {
return
}
if (!settings || !settings.root) {
throw new Error('settings.root is required')
}
settings.root = path.resolve(process.cwd(), settings.root)
copy(defaults).to(settings)
settings.ext = settings.ext ? '.' + settings.ext.replace(/^\./, '') : ''
function * render (view, options) {
view += settings.ext
const viewPath = path.join(settings.root, view)
const source = yield fs.readFile(viewPath, 'utf8')
options = settings.options || {}
const plugins = settings.plugins || []
if (options.sync) {
return posthtml(plugins)
.process(source, options)
.html
} else {
return posthtml(plugins)
.process(source, options)
.then((result) => result.html)
}
}
app.context.render = function * (view, options) {
const html = yield * render(view, options)
if (settings.writeResp) {
// send response
this.type = 'html'
this.body = html
} else {
// only return the html
return html
}
}
}