Skip to content

Instantly share code, notes, and snippets.

@tspringborg
Created June 9, 2020 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tspringborg/4bd1007d84c3284057f67d36be44ddb1 to your computer and use it in GitHub Desktop.
Save tspringborg/4bd1007d84c3284057f67d36be44ddb1 to your computer and use it in GitHub Desktop.
nodejs index.js for twigjs templates
/*
https://twig.symfony.com/doc/3.x/templates.html (note this is php but syntax is similar (mostly)
https://github.com/twigjs/twig.js/wiki/Implementation-Notes
*/
const fs = require('fs');
const Twig = require('twig');
const renderFunction = Twig.twig;
let templates = {};
const files = fs.readdirSync(__dirname + '/');
files.forEach((file) => {
if (file.match(/\.twig$/) !== null) {
const fileName = file.replace(/\.twig$/, '');
const string = fs.readFileSync(__dirname + '/'+ file, 'utf8');
const template = renderFunction({
allowInlineIncludes: true,
data: string,
ref: fileName,
base: __dirname,
});
templates[fileName] = template;
}
});
Twig.extendFunction("template", function(name, data) {
return templates[name].render(data);
});
module.exports = templates;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment