Licence
ISC
Version
1.1.0
Deps
0
Size
7 kB
Vulns
0
Weekly
0
template-literal-file
Have template literals in their own file and compile them to a function.
Installation
npm install template-literal-file
Usage
Load a template literal file using the renderFile function:
import { renderFile } from 'template-literal-file';
const template = renderFile('./test.html');
const html = template({ myVar: 'test' });
console.log(html); // <div>test</div>
Template literal file
<div>${myVar}</div>
The object keys passed to the returned function become variables inside the template. Any JavaScript expression valid inside a template literal works:
<ul>${items.map(i => `<li>${i}</li>`).join('')}</ul>
API
renderFile(filePath)
Reads the file at filePath and returns a reusable template function. The file is read once and cached — subsequent calls with the same path return the cached function.
- Relative paths (e.g.
./template.html) resolve against the directory of the file that callsrenderFile. - Root-relative paths (starting with
/, e.g./templates/page.html) resolve againstprocess.cwd().
templateFn(vars?)
The function returned by renderFile. Accepts an optional plain object; each key becomes a variable name available inside the template.
Security
Template files are executed via new Function(). Treat them as trusted code — do not render template files from untrusted sources.