-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (55 loc) · 1.42 KB
/
index.js
File metadata and controls
69 lines (55 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
69
/**
* Handlebars driver for Sapling
*/
/* Dependencies */
import fs from 'node:fs';
import path from 'node:path';
import handlebars from 'handlebars';
import Interface from '@sapling/sapling/drivers/render/Interface.js';
import SaplingError from '@sapling/sapling/lib/SaplingError.js';
export default class Handlebars extends Interface {
/**
* Initialise Handlebars
*/
constructor(App, viewsPath) {
super();
this.app = App;
this.viewsPath = viewsPath;
this.engine = handlebars;
}
/**
* Render a template file
*
* @param {string} template Path of the template file being rendered, relative to views/
* @param {object} data Object of data to pass to the template
*/
async render(template, data) {
let rendered;
try {
const file = fs.readFileSync(path.join(this.viewsPath, template));
rendered = this.engine.compile(file.toString());
} catch (error) {
return new SaplingError(error);
}
return rendered(data);
}
/**
* Register custom tags with the template engine
*
* @param {object} tags Object of functions
*/
async registerTags(tags) {
for (const tag in tags) {
if (Object.prototype.hasOwnProperty.call(tags, tag)) {
if (tag === 'get') {
this.engine.registerHelper(tag, (variable, eq, url, as, role) => {
this[variable] = tags.get(url, role || null);
return '';
});
} else {
this.engine.registerHelper(tag, tags[tag]);
}
}
}
}
}