-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtasks.js
64 lines (57 loc) · 1.66 KB
/
tasks.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// file system
const { stat } = require('fs');
const process = require('process');
const { resolve } = require('path');
// modules
const Twig = require('twig');
/**
* Retrieves options from the configuration file
* @returns {object}
*/
function retrieveOptions() {
const cwd = process.cwd();
const file = resolve(cwd, 'twig.config.js');
stat(file, function(err, stat) {
if (err && err.code === 'ENOENT') return false;
if (err === null) {
try {
return require(file);
} catch (e) {
console.error(`Require ${file} faild:\n`, e);
}
} else {
console.error('File system error: ', err.code);
}
});
return {};
}
/**
* It handles Twig configuration and extension
* @param {object} extensions
*/
function configureTwig({ functions = {}, filters = {} } = {}) {
Twig.cache(false);
Object.entries(filters).forEach(([key, fn]) => Twig.extendFilter(key, fn));
Object.entries(functions).forEach(([key, fn]) => Twig.extendFunction(key, fn));
}
/**
* It handles the conversion from twig to html
* @param {string} template The twig template filepath
* @param {object} context The data to be injected in the template
* @param {object} settings The twig settings
* @returns {Promise}
*/
function renderTemplate(template, context = {}, settings = {}) {
return new Promise((resolve, reject) => {
Twig.renderFile(template, { ...context, settings }, (err, html) => {
if (err) {
reject(err);
} else {
resolve(html);
}
});
});
}
module.exports.retrieveOptions = retrieveOptions;
module.exports.configureTwig = configureTwig;
module.exports.renderTemplate = renderTemplate;