forked from nodeSolidServer/node-solid-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate-utils.js
More file actions
50 lines (45 loc) · 1.42 KB
/
template-utils.js
File metadata and controls
50 lines (45 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
module.exports.compileTemplate = compileTemplate
module.exports.processHandlebarFile = processHandlebarFile
module.exports.writeTemplate = writeTemplate
const Handlebars = require('handlebars')
const debug = require('../debug').errors
const { processFile, readFile, writeFile } = require('./fs-utils')
async function compileTemplate (filePath) {
const indexTemplateSource = readFile(filePath)
return Handlebars.compile(indexTemplateSource)
}
/**
* Reads a file, processes it (performing template substitution), and saves
* back the processed result.
*
* @param filePath {string}
* @param substitutions {Object}
*
* @return {Promise}
*/
async function processHandlebarFile (filePath, substitutions) {
return processFile(filePath, (rawSource) => processHandlebarTemplate(rawSource, substitutions))
}
/**
* Performs a Handlebars string template substitution, and returns the
* resulting string.
*
* @see https://www.npmjs.com/package/handlebars
*
* @param source {string} e.g. 'Hello, {{name}}'
*
* @return {string} Result, e.g. 'Hello, Alice'
*/
function processHandlebarTemplate (source, substitutions) {
try {
const template = Handlebars.compile(source)
return template(substitutions)
} catch (error) {
debug(`Error processing template: ${error}`)
return source
}
}
function writeTemplate (filePath, template, substitutions) {
const source = template(substitutions)
writeFile(filePath, source)
}