Skip to content

Instantly share code, notes, and snippets.

@piratefsh
Created December 9, 2021 22:15
Show Gist options
  • Save piratefsh/bf7b570270ba7157b149294ee5ee4aaf to your computer and use it in GitHub Desktop.
Save piratefsh/bf7b570270ba7157b149294ee5ee4aaf to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
const fs = require('fs');
const jSmart = require('../../jsmart');
const tpl = fs.readFileSync('./test-file.tpl', {encoding: 'utf-8'});
debugger;
const compiledTemplate = new jSmart(tpl, {autoLiteral: false, ldelim: "{%", rdelim: "%}"});
// const output = compiledTemplate.fetch({my_variable: 'Hello World', my_conditional: true});
// // output will be "Hello world"
const tree = compiledTemplate.tree;
function transpile(tree){
let transpiled = "";
for(let i = 0; i < tree.length; i++) {
const node = tree[i];
switch(node.type) {
case 'text':
transpiled += node.data
continue;
case 'build-in':
if(node.name === 'expression') {
const { expression } = node;
if(expression && expression.type == 'var') {
const { parts } = expression;
parts.map(({type, data}) => {
transpiled += `{{${data}}}`
});
}
} else if (node.name === 'if') {
const ifBlock = transpile(node.subTreeIf);
const elseBlock = transpile(node.subTreeElse);
const conditional = node.params.toString().slice(1);
transpiled += `{{#${conditional}}}${ifBlock}{{/${conditional}}}`
transpiled += `{{^${conditional}}}${elseBlock}{{/${conditional}}}`
} else {
debugger
}
continue
default:
transpiled += node.data
continue;
}
}
return transpiled
}
// console.log(output);
console.log("Original:\n", tpl)
console.log("Mustache\n", transpile(tree));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment