58 lines
1.3 KiB
TypeScript
58 lines
1.3 KiB
TypeScript
|
|
import { Config } from './conf';
|
|
import { render as mustache_render } from 'mustache';
|
|
import { promises as fs } from 'fs';
|
|
import { resolve as resolve_path } from 'path';
|
|
import { glob } from 'glob';
|
|
|
|
export interface Context {
|
|
env?: Record<string, string>;
|
|
page?: {
|
|
title?: string;
|
|
layout?: string;
|
|
[key: string]: string | number | boolean;
|
|
};
|
|
build_time: {
|
|
iso: string;
|
|
rfc2822: string;
|
|
};
|
|
}
|
|
|
|
export function render_template(template: string, context: Context, layout?: string, partials?: Record<string, string>) {
|
|
partials['.content'] = template;
|
|
return mustache_render(layout || template, context, partials);
|
|
}
|
|
|
|
export async function load_layout(conf: Config, file: string) {
|
|
const path = conf.templates?.layouts;
|
|
|
|
if (! path) {
|
|
return null;
|
|
}
|
|
|
|
const rel_path = resolve_path('/', file);
|
|
const abs_path = resolve_path(path, '.' + rel_path);
|
|
return await fs.readFile(abs_path, 'utf8');
|
|
}
|
|
|
|
export async function load_partials(conf: Config) {
|
|
const path = conf.templates?.partials;
|
|
|
|
if (! path) {
|
|
return { };
|
|
}
|
|
|
|
const partials: Record<string, string> = { };
|
|
const partial_files = await glob(path + '/**/*', {
|
|
cwd: path,
|
|
absolute: false,
|
|
});
|
|
|
|
for (const file of partial_files) {
|
|
const abs_file = resolve_path(path, file);
|
|
partials[file] = await fs.readFile(abs_file, 'utf8');
|
|
}
|
|
|
|
return partials;
|
|
}
|