74 lines
2.6 KiB
JavaScript
74 lines
2.6 KiB
JavaScript
"use strict";
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.Templates = void 0;
|
|
const handlebars_1 = __importDefault(require("handlebars"));
|
|
const handlebars_helpers_1 = __importDefault(require("handlebars-helpers"));
|
|
const promises_1 = require("fs/promises");
|
|
const path_1 = require("path");
|
|
const log_1 = require("../log");
|
|
(0, handlebars_helpers_1.default)();
|
|
class Templates {
|
|
constructor(dir = './views') {
|
|
this.templates = {};
|
|
this.dir = dir;
|
|
this.log = (0, log_1.createLog)('tmpl');
|
|
}
|
|
async build() {
|
|
const partialsPath = (0, path_1.join)(this.dir, 'partials');
|
|
let partials = [];
|
|
let templates = [];
|
|
let text;
|
|
let name;
|
|
try {
|
|
partials = await (0, promises_1.readdir)(partialsPath);
|
|
}
|
|
catch (err) {
|
|
this.log.error(err);
|
|
}
|
|
partials = partials.map(el => (0, path_1.join)(partialsPath, el));
|
|
for (let partial of partials) {
|
|
name = (0, path_1.parse)((0, path_1.basename)(partial)).name;
|
|
try {
|
|
text = await (0, promises_1.readFile)(partial, 'utf8');
|
|
}
|
|
catch (err) {
|
|
this.log.error(err);
|
|
continue;
|
|
}
|
|
handlebars_1.default.registerPartial(name, text);
|
|
this.log.info(`[partial] ${name}`);
|
|
}
|
|
try {
|
|
templates = await (0, promises_1.readdir)(this.dir);
|
|
}
|
|
catch (err) {
|
|
this.log.error(err);
|
|
}
|
|
templates = templates
|
|
.filter(el => el.indexOf('.hbs') !== -1 || el.indexOf('.handlebars') !== -1)
|
|
.map(el => (0, path_1.join)(this.dir, el));
|
|
for (let template of templates) {
|
|
name = (0, path_1.parse)((0, path_1.basename)(template)).name;
|
|
try {
|
|
text = await (0, promises_1.readFile)(template, 'utf8');
|
|
}
|
|
catch (err) {
|
|
this.log.error(err);
|
|
continue;
|
|
}
|
|
this.templates[name] = handlebars_1.default.compile(text);
|
|
this.log.info(`[template] ${name}`);
|
|
}
|
|
}
|
|
render(name, data) {
|
|
const keys = Object.keys(data);
|
|
this.log.info(`[render] ${name} with keys { ${keys.join(', ')} }`);
|
|
return this.templates[name](data);
|
|
}
|
|
}
|
|
exports.Templates = Templates;
|
|
module.exports = { Templates };
|
|
//# sourceMappingURL=index.js.map
|