-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
94 lines (76 loc) · 2.23 KB
/
index.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const Handlebars = require("handlebars");
const matter = require("gray-matter");
const fs = require("fs");
const path = require("path");
const loadFiles = require("./lib/loadFiles");
const loadContents = require("./lib/loadContents");
/**
* Create a new compilator
* @class
* @example
* var compile = new Compilator({
* helpers: 'helpers/',
* layouts: 'layouts/',
* partials: 'partials/'
* });
* compile.render('pages/test.hbs', {
* title: 'Hello Evryone'
* }); => return html elements
*/
class Compilator {
/**
*
* @param {Object} options
* @param {string} options.helpers - path to helpers
* @param {string} options.layouts - path to layouts
* @param {string} options.partials - path to partials
*/
constructor(options) {
this.Handlebars = Handlebars;
this.layouts = [];
this.options = options || {};
this.loadHelpers();
this.loadLayouts();
this.loadPartials();
}
loadHelpers() {
if (!this.options || !this.options.helpers) return;
const helpers = loadFiles(this.options.helpers);
helpers.forEach((helper) => {
const h = require(helper);
this.Handlebars.registerHelper(path.basename(helper, ".js"), h);
});
}
loadLayouts() {
if (!this.options || !this.options.layouts) return;
const layouts = loadContents(this.options.layouts);
layouts.forEach(
({ name, content }) =>
(this.layouts[name] = this.Handlebars.compile(content))
);
}
loadPartials() {
if (!this.options || !this.options.partials) return;
const partials = loadContents(this.options.partials);
partials.forEach(({ name, content }) =>
this.Handlebars.registerPartial(name, content)
);
}
/**
*
* @param {string} file - path to page
* @param {Object} data
*/
render(file, data) {
if (!file) return;
file = fs.readFileSync(file, "utf8");
const page = matter(file);
const options = page.data;
const layoutPage = options.layout || "default";
const layoutTemplate = this.layouts[layoutPage];
const pageTemplate = this.Handlebars.compile(page.content + "\n");
this.Handlebars.registerPartial("body", pageTemplate);
return layoutTemplate({ ...options, ...data });
}
}
module.exports = Compilator;