/
render.ts
65 lines (55 loc) · 1.48 KB
/
render.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
import compile from "./compile.ts";
import { getConfig } from "./config.ts";
/* TYPES */
import { EtaConfig, PartialConfig } from "./config.ts";
import { TemplateFunction } from "./compile.ts";
import { CallbackFn } from "./file-handlers.ts";
/* END TYPES */
function handleCache(
template: string | TemplateFunction,
options: EtaConfig,
): TemplateFunction {
var templateFunc;
if (options.cache && options.name && options.templates.get(options.name)) {
return options.templates.get(options.name);
}
if (typeof template === "function") {
templateFunc = template;
} else {
templateFunc = compile(template, options);
}
if (options.cache && options.name) {
options.templates.define(options.name, templateFunc);
}
return templateFunc;
}
export default function render(
template: string | TemplateFunction,
data: object,
env?: PartialConfig,
cb?: CallbackFn,
) {
var options = getConfig(env || {});
if (options.async) {
var result;
if (!cb) {
// No callback, try returning a promise
return new Promise(function (resolve: Function, reject: Function) {
try {
result = handleCache(template, options)(data, options);
resolve(result);
} catch (err) {
reject(err);
}
});
} else {
try {
handleCache(template, options)(data, options, cb);
} catch (err) {
return cb(err);
}
}
} else {
return handleCache(template, options)(data, options);
}
}