-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
68 lines (65 loc) · 1.82 KB
/
mod.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
import { Handler, HttpResponse } from "https://deno.land/x/[email protected]/mod.ts";
import nunjucks from "https://deno.land/x/[email protected]/mod.js";
export type TViewOptions = {
autoescape?: boolean;
throwOnUndefined?: boolean;
trimBlocks?: boolean;
lstripBlocks?: boolean;
noCache?: boolean;
web?: {
useCache?: boolean;
async?: boolean;
};
tags?: {
blockStart: string;
blockEnd: string;
variableStart: string;
variableEnd: string;
commentStart: string;
commentEnd: string;
};
[k: string]: any;
};
export type TViewOptionsCustom = {
basedir?: string;
extname?: string;
};
export class ViewEngine {
response!: HttpResponse & {
view: (name: string, params?: Record<string, any>, ...args: any) => any;
};
static init(opts: TViewOptions & TViewOptionsCustom = {}): Handler {
opts.basedir = opts.basedir || "views";
opts.extname = opts.extname || ".html";
nunjucks.configure(opts.basedir, opts);
return (rev, next) => {
rev.response.view = (
name: string,
params?: Record<string, any>,
) => {
if (name.lastIndexOf(".") === -1) {
name = name + opts.extname;
}
const html = nunjucks.render(name, params);
rev.response.type("text/html; charset=utf-8").send(html);
};
next();
};
}
static custom(render: any, opts: TViewOptionsCustom = {}): Handler {
opts.basedir = opts.basedir || "";
opts.extname = opts.extname || ".html";
return (rev, next) => {
rev.response.view = async (
name: string,
params?: Record<string, any>,
...args: any
) => {
name = opts.basedir + name + opts.extname;
const html = await render(name, params, ...args);
rev.response.type("text/html; charset=utf-8").send(html);
};
next();
};
}
}