-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhandlebars.ts
86 lines (66 loc) · 2.44 KB
/
handlebars.ts
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
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */
import fs from 'node:fs';
import * as _ from 'underscore';
import {helpers, handlebars} from '@jaredwray/fumanchu';
import {BaseEngine} from '../base-engine.js';
import type {EngineInterface} from '../engine-interface.js';
export class Handlebars extends BaseEngine implements EngineInterface {
public partialsPath = ['partials', 'includes', 'templates'];
constructor(options?: Record<string, unknown>) {
super();
this.names = ['handlebars', 'mustache'];
this.opts = options;
this.engine = handlebars;
// Register helpers
helpers({handlebars}, this.opts);
this.setExtensions(['hbs', 'hjs', 'handlebars', 'mustache']);
}
async render(source: string, data?: Record<string, unknown>): Promise<string> {
// Register partials
if (this.rootTemplatePath) {
this.initPartials();
}
const template = this.engine.compile(source, this.opts);
let result = template(data, this.opts);
result = _.unescape(result);
return result;
}
renderSync(source: string, data?: Record<string, unknown>): string {
// Register partials
if (this.rootTemplatePath) {
this.initPartials();
}
const template = this.engine.compile(source, this.opts);
let result = template(data, this.opts);
result = _.unescape(result);
return result;
}
initPartials(): void {
for (const path of this.partialsPath) {
const fullPath = `${this.rootTemplatePath}/${path}`;
this.registerPartials(fullPath);
}
}
registerPartials(partialsPath: string): boolean {
let result = false;
if (fs.existsSync(partialsPath)) {
const partials = fs.readdirSync(partialsPath, {recursive: true, encoding: 'utf8'});
for (const p of partials) {
if (fs.statSync(partialsPath + '/' + p).isDirectory()) {
const directoryPartials = fs.readdirSync(partialsPath + '/' + p, {recursive: true, encoding: 'utf8'});
for (const dp of directoryPartials) {
const source = fs.readFileSync(partialsPath + '/' + p + '/' + dp).toString();
const name = p + '/' + dp.split('.')[0];
this.engine.registerPartial(name, this.engine.compile(source));
}
} else {
const source = fs.readFileSync(partialsPath + '/' + p, 'utf8');
const name = p.split('.')[0];
this.engine.registerPartial(name, this.engine.compile(source));
}
}
result = true;
}
return result;
}
}