1 | import {Injectable} from "@angular/core";
|
2 | import {isDefined} from "./util";
|
3 |
|
4 | export abstract class TranslateParser {
|
5 | |
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | abstract interpolate(expr: string | Function, params?: any): string | undefined;
|
12 |
|
13 | |
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | abstract getValue(target: any, key: string): any
|
20 | }
|
21 |
|
22 | @Injectable()
|
23 | export class TranslateDefaultParser extends TranslateParser {
|
24 | templateMatcher: RegExp = /{{\s?([^{}\s]*)\s?}}/g;
|
25 |
|
26 | public interpolate(expr: string | Function, params?: any): string {
|
27 | let result: string;
|
28 |
|
29 | if (typeof expr === 'string') {
|
30 | result = this.interpolateString(expr, params);
|
31 | } else if (typeof expr === 'function') {
|
32 | result = this.interpolateFunction(expr, params);
|
33 | } else {
|
34 |
|
35 | result = expr as string;
|
36 | }
|
37 |
|
38 | return result;
|
39 | }
|
40 |
|
41 | getValue(target: any, key: string): any {
|
42 | let keys = typeof key === 'string' ? key.split('.') : [key];
|
43 | key = '';
|
44 | do {
|
45 | key += keys.shift();
|
46 | if (isDefined(target) && isDefined(target[key]) && (typeof target[key] === 'object' || !keys.length)) {
|
47 | target = target[key];
|
48 | key = '';
|
49 | } else if (!keys.length) {
|
50 | target = undefined;
|
51 | } else {
|
52 | key += '.';
|
53 | }
|
54 | } while (keys.length);
|
55 |
|
56 | return target;
|
57 | }
|
58 |
|
59 | private interpolateFunction(fn: Function, params?: any) {
|
60 | return fn(params);
|
61 | }
|
62 |
|
63 | private interpolateString(expr: string, params?: any) {
|
64 | if (!params) {
|
65 | return expr;
|
66 | }
|
67 |
|
68 | return expr.replace(this.templateMatcher, (substring: string, b: string) => {
|
69 | let r = this.getValue(params, b);
|
70 | return isDefined(r) ? r : substring;
|
71 | });
|
72 | }
|
73 | }
|