-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
url.ts
42 lines (35 loc) 路 990 Bytes
/
url.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
import { merge } from "../core/utils.ts";
import type { Helper, Site } from "../core.ts";
export interface Options {
/** The url helper name */
names: {
url: string;
htmlUrl: string;
};
}
export const defaults: Options = {
names: {
url: "url",
htmlUrl: "htmlUrl",
},
};
/**
* A plugin to register the filters "url" and "htmlUrl"
* for normalizing URLs in the templates
*/
export default function (userOptions?: Partial<Options>) {
const options = merge(defaults, userOptions);
return (site: Site) => {
site.filter(options.names.url, url as Helper);
site.filter(options.names.htmlUrl, htmlUrl as Helper);
function url(path = "/", absolute = false) {
return typeof path === "string" ? site.url(path, absolute) : path;
}
function htmlUrl(html = "", absolute = false) {
return html.replaceAll(
/\s(href|src)="([^"]+)"/g,
(_match, attr, value) => ` ${attr}="${url(value, absolute)}"`,
);
}
};
}