UNPKG

@foal/core

Version:

Full-featured Node.js framework, with no complexity

60 lines (59 loc) 2.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.renderToString = renderToString; exports.render = render; // std const promises_1 = require("node:fs/promises"); const path_1 = require("path"); // FoalTS const http_1 = require("../http"); const config_1 = require("../config"); /** * Util function to render a template. Minimalist built-in template engine for FoalTS. * * renderToString('Hello {{ name }}!', { name: 'Mary' }) returns 'Hello Mary!' * * @export * @param {string} template - The template. * @param {any} locals - The variables required by the template. * @returns {string} The rendered template. */ function renderToString(template, locals) { for (const key in locals) { template = template.replace(new RegExp(`{{ ${key} }}`, 'g'), locals[key]); } return template; } /** * Render a template in a new HttpResponseOK object. * * The template engine is specified using the configuration key `settings.templateEngine`. * * @export * @param {string} templatePath - The path of the template. * @param {object} locals - The variables used to render the template. * @param {string} [dirname] - The directory name where the templated is located. * The passed value is usually `__dirname`. The function then joins `dirname` and * `templatePath` together. * @returns {Promise<HttpResponseOK>} */ async function render(templatePath, locals = {}, dirname) { const path = dirname ? (0, path_1.join)(dirname, templatePath) : templatePath; const template = await (0, promises_1.readFile)(path, 'utf8'); const templateEngine = config_1.Config.get('settings.templateEngine', 'string'); if (templateEngine) { const { __express } = require(templateEngine); if (__express) { return new Promise((resolve, reject) => { __express(path, locals, (err, html) => { if (err) { return reject(err); } resolve(new http_1.HttpResponseOK(html)); }); }); } throw new Error(`${templateEngine} is not a template engine compatible with FoalTS.`); } return new http_1.HttpResponseOK(renderToString(template, locals)); }