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; 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) { 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 = { }; 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; }