Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Prevent lodash.template from interfering with javascript string inter…
…polation Closes #3468
- Loading branch information
Showing
3 changed files
with
96 additions
and
42 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
const { template } = require('lodash'); | ||
const { promisify } = require('util'); | ||
const fs = require('fs'); | ||
|
||
/** | ||
* Light wrapper over lodash templates making it safer to be used with javascript source code. | ||
* | ||
* In particular, doesn't interfere with use of interpolated strings in javascript. | ||
* | ||
* @param {string} content Template source | ||
* @param {_.TemplateOptions} options Template options | ||
*/ | ||
const jsSourceTemplate = (content, options) => | ||
template(content, { | ||
interpolate: /<%=([\s\S]+?)%>/g, | ||
...options, | ||
}); | ||
|
||
const readFile = promisify(fs.readFile, { context: fs }); | ||
const writeFile = promisify(fs.writeFile, { context: fs }); | ||
|
||
/** | ||
* Compile the contents of specified (javascript) file as a lodash template | ||
* | ||
* @param {string} filePath Path of file to be used as template | ||
* @param {_.TemplateOptions} options Lodash template options | ||
*/ | ||
const jsFileTemplate = async (filePath, options) => { | ||
const contentBuffer = await readFile(filePath); | ||
return jsSourceTemplate(contentBuffer.toString(), options); | ||
}; | ||
|
||
/** | ||
* Write a javascript file using another file as a (lodash) template | ||
* | ||
* @param {string} targetFilePath | ||
* @param {string} sourceFilePath | ||
* @param {_.TemplateOptions} options options passed to lodash templates | ||
*/ | ||
const writeJsFileUsingTemplate = async ( | ||
targetFilePath, | ||
sourceFilePath, | ||
options, | ||
variables | ||
) => writeFile(targetFilePath, (await jsFileTemplate(sourceFilePath, options))(variables)); | ||
|
||
module.exports = { | ||
jsSourceTemplate, | ||
jsFileTemplate, | ||
writeJsFileUsingTemplate | ||
}; |