-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.ts
34 lines (27 loc) · 1.09 KB
/
template.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
import fs from 'fs';
const baseDir = './templates';
type TemplateData = {
[key: string]: any;
};
export default function getTemplate(template: string, data: TemplateData = {}): string {
const templatePath = `${baseDir}/${template}.html`;
if (!fs.existsSync(templatePath)) {
throw new Error(`Template not found: ${template}`);
}
let templateContent = fs.readFileSync(templatePath, 'utf-8');
// Fill in data into template {{ key }}
templateContent = templateContent.replace(/{{\s*([^}]+)\s*}}/g, (match, key) => {
const content = data[key.trim()];
if (content === undefined) {
return "undefined";
} else {
return content.toString();
}
});
// Replace relative paths
templateContent = templateContent.replace(/"..\/static\//g, '"/static/');
templateContent = templateContent.replace(/'..\/static\//g, "'/static/");
templateContent = templateContent.replace(/=..\/static\//g, "='/static/");
templateContent = templateContent.replace(/url\('..\/static\//g, "url('/static/");
return templateContent;
}