-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathTemplateCompiler.ts
More file actions
38 lines (30 loc) · 1.17 KB
/
TemplateCompiler.ts
File metadata and controls
38 lines (30 loc) · 1.17 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
import {TokenValueDTO} from './types';
class TemplateCompiler {
private _template = '';
private _tokens: Token[] = [];
private _tokenValues: TokenValueDTO = {};
private _reduceEmptyLines = true;
constructor(template: string[], tokens: Token[], tokenValues: TokenValueDTO) {
this._template = template.join('\n');
this._tokens = tokens;
this._tokenValues = tokenValues;
}
set reduceEmptyLines(val: boolean) {
this._reduceEmptyLines = val;
}
compile(): string {
let compiled = this._template;
this._tokens.forEach(({ name, prefix = '', suffix = '', isConditionalToken, linkedToken, matchValue }) => {
let value = this._tokenValues[name] || '';
const canShowConditionallyRendered = !isConditionalToken || !linkedToken || this._tokenValues[linkedToken.name] === matchValue;
value = value && canShowConditionallyRendered ? prefix + value + suffix : '';
compiled = compiled.replace(new RegExp(`{${name}}`, 'g'), value);
});
if (this._reduceEmptyLines) {
compiled = compiled.replace(/\n{3,}/g, '\n\n');
compiled = compiled.replace(/\n+$/g, '');
}
return compiled;
}
}
export default TemplateCompiler;