Skip to content

Instantly share code, notes, and snippets.

@webarthur
Created July 10, 2023 18:12
Show Gist options
  • Save webarthur/abc6d68a44451d0bcb02a2966213a689 to your computer and use it in GitHub Desktop.
Save webarthur/abc6d68a44451d0bcb02a2966213a689 to your computer and use it in GitHub Desktop.
A simple template literals engine as a function for Node.js
const { readFileSync } = require('fs')
const { resolve } = require('path')
// Resolving the absolute path of the 'views' directory
const viewDir = resolve(`${ __dirname }/views/`)
/**
* Renders a view with the provided data.
* @param {string} viewName - The name of the view to render.
* @param {object} data - The data to pass to the view.
* @returns {string} The rendered view as a string.
* @throws {Error} If there is an error while rendering the view.
*/
function render (viewName, data) {
try {
// Read the contents of the view file
const view = readFileSync(`${ viewDir }/${ viewName }.view.html`, 'utf8')
// Creating a new function dynamically using the contents of the view file
const template = new Function('data', `
with (data)
return \`${ view }\`
`)
// Rendering the view template with the provided data
return template(data)
}
cache (error) {
throw error // If an error occurs during the rendering process, throw it
}
}
module.exports = render
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment