This repository was archived by the owner on Mar 26, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfp-handlebars.js
More file actions
89 lines (78 loc) · 2.22 KB
/
fp-handlebars.js
File metadata and controls
89 lines (78 loc) · 2.22 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var fs = require('fs');
var path = require('path');
const templateDir = path.join(__dirname, 'templates')
const helperDir = path.join(__dirname, 'helpers')
//TODO: This needs better (some!) error handling
var Handlebars = (function(){
var handlebarsInstance;
var createHandlebarsInstance = function() {
var hbs = require('handlebars')
var templates = {};
//register helpers
var helpers = require('./helpers/handlebars-helpers')
Object.getOwnPropertyNames(helpers).forEach(function(key){
if (typeof helpers[key] == "function") {
hbs.registerHelper(key, helpers[key])
}
})
//register partials
var partials = [];
fs.readdirSync(path.join(templateDir, 'partials')).forEach(filename => {
var result = readFileAsync(path.join(templateDir, 'partials', filename))
.then(function(data){
var name = filename.replace('.handlebars', '');
hbs.registerPartial(name, data);
})
.catch(function(err) {
console.log(err)
})
partials.push(result)
})
Promise.all(partials)
.then(function(){
console.log("All partials registered")
//compile the templates
fs.readdirSync(templateDir).forEach(templateFile => {
fs.lstat(path.join(templateDir, templateFile), function(err, stats) {
if (stats.isFile()) {
readFileAsync(path.join(templateDir, templateFile))
.then(function(data){
var key = templateFile.replace('.handlebars', '');
templates[key] = hbs.compile(data);
})
.catch(function(err) {
console.log(err)
})
}
})
})
})
function getTemplate(name) {
return templates[name]
}
return {
getTemplate: getTemplate
}
}
return {
getInstance : function() {
if (!handlebarsInstance) {
handlebarsInstance = createHandlebarsInstance();
}
return handlebarsInstance
}
}
})();
module.exports = Handlebars;
function readFileAsync(file) {
return new Promise(function(resolve,reject) {
fs.readFile(file, 'utf8', function(err, data) {
if (err) {
reject(err)
}
else {
resolve(data)
}
})
})
}