-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
53 lines (53 loc) · 1.54 KB
/
index.mjs
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
import vm from 'node:vm'
class Template {
constructor (template, data, partials = new Map(), functions = {}) {
this.template = template
this.data = data
this.partials = partials
this.functions = functions
}
renderWithLayout (layout, body) {
if (!layout || layout.length === 0) {
return body
}
const sandbox = {
...this.data,
...this.functions,
body,
}
const script = new vm.Script(`result = \`${layout}\``)
const context = new vm.createContext(sandbox)
script.runInContext(context)
return context.result
}
async render() {
let layout = null
const hasLayout = layoutPath => {
layout = layoutPath
return ''
}
const script = new vm.Script(`result = \`${this.template}\``)
const context = new vm.createContext({
...this.data,
...this.functions,
hasLayout
})
try {
script.runInContext(context, {displayErrors: true})
} catch (e) {
throw e
}
if (layout) {
context.result = context.result?.replace(/^\n/, '')
return this.renderWithLayout(this.partials.get(layout), context.result)
}
if (layout) {
context.result = context.result.replace(/^\n/, '')
return this.renderWithLayout(this.partials.get(layout), context.result)
}
return context.result
}
}
export {
Template
}