UNPKG

@thi.ng/transclude

Version:

Extensible functional template engine for text document generation, incl. various high-level Markdown features

42 lines (41 loc) 1.13 kB
import { readText } from "@thi.ng/file-io/text"; import { ConsoleLogger } from "@thi.ng/logger"; import { resolve } from "node:path"; const DEFAULT_LOGGER = new ConsoleLogger("transclude"); const transclude = (ctx, path) => { const $ctx = { logger: DEFAULT_LOGGER, match: /\{\{([a-z0-9.]+)([^}]*)\}\}/gi, pre: [], post: [], eol: "\n", ...ctx }; $ctx.pre.reduce((acc, fn) => $ctx.src = fn($ctx, [acc], path), $ctx.src); $ctx.src = $ctx.src.replace($ctx.match, (...args) => { const [orig, id] = args; const tpl = $ctx.templates[id]; if (tpl !== void 0) { return typeof tpl === "function" ? tpl($ctx, args, path) : tpl; } else { $ctx.logger.warn(`skipping unknown tpl ID: "${id}"`); return orig; } }); $ctx.post.reduce((acc, fn) => $ctx.src = fn($ctx, [acc], path), $ctx.src); return $ctx; }; const transcludeFile = (path, ctx) => { const $ctx = { logger: DEFAULT_LOGGER, src: "", ...ctx }; path = resolve(path); $ctx.src = readText(path, $ctx.logger); return transclude($ctx, path); }; export { transclude, transcludeFile };