-
Notifications
You must be signed in to change notification settings - Fork 171
/
handlebars.adapter.ts
87 lines (75 loc) 路 2.36 KB
/
handlebars.adapter.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
87
/** Dependencies **/
import * as fs from 'fs';
import * as path from 'path';
import * as handlebars from 'handlebars';
import * as inlineCss from 'inline-css';
import * as glob from 'glob';
import { get } from 'lodash';
/** Interfaces **/
import { MailerOptions } from '../interfaces/mailer-options.interface';
import { TemplateAdapter } from '../interfaces/template-adapter.interface';
export class HandlebarsAdapter implements TemplateAdapter {
private precompiledTemplates: {
[name: string]: handlebars.TemplateDelegate;
} = {};
constructor() {
handlebars.registerHelper('concat', (...args) => {
args.pop();
return args.join('');
});
}
public compile(mail: any, callback: any, mailerOptions: MailerOptions): void {
const precompile = (template: any, callback: any, options: any) => {
const templateExt = path.extname(template) || '.hbs';
const templateName = path.basename(template, path.extname(template));
const templateDir =
path.dirname(template) !== '.'
? path.dirname(template)
: get(options, 'dir', '');
const templatePath = path.join(templateDir, templateName + templateExt);
if (!this.precompiledTemplates[templateName]) {
try {
const template = fs.readFileSync(templatePath, 'UTF-8');
this.precompiledTemplates[templateName] = handlebars.compile(
template,
get(options, 'options', {}),
);
} catch (err) {
return callback(err);
}
}
return {
templateExt,
templateName,
templateDir,
templatePath,
};
};
const { templateName } = precompile(
mail.data.template,
callback,
mailerOptions.template,
);
const runtimeOptions = get(mailerOptions, 'options', {
partials: false,
data: {},
});
if (runtimeOptions.partials) {
const files = glob.sync(path.join(runtimeOptions.partials.dir, '*.hbs'));
files.forEach((file) =>
precompile(file, () => {}, runtimeOptions.partials),
);
}
const rendered = this.precompiledTemplates[templateName](
mail.data.context,
{
...runtimeOptions,
partials: this.precompiledTemplates,
},
);
inlineCss(rendered, { url: ' ' }).then((html) => {
mail.data.html = html;
return callback();
});
}
}