Skip to content

Instantly share code, notes, and snippets.

@javanigus
Last active August 1, 2023 01:36
Show Gist options
  • Save javanigus/1fc9aff9d492c834e0cf9ccc2fdd15b8 to your computer and use it in GitHub Desktop.
Save javanigus/1fc9aff9d492c834e0cf9ccc2fdd15b8 to your computer and use it in GitHub Desktop.
Convert handlebars to nunjucks
const fs = require('fs');
const path = require('path');
const walk = dir => {
try {
let results = [];
const list = fs.readdirSync(dir);
list.forEach(file => {
file = path.join(dir, file);
const stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
// Recurse into subdir
results = [...results, ...walk(file)];
} else {
// Is a file
results.push(file);
}
});
return results;
} catch (error) {
console.error(`Error when walking dir ${dir}`, error);
}
};
const edit = filePath => {
if (filePath.endsWith('hbs')) {
var oldContent = fs.readFileSync(filePath, {encoding: 'utf8'});
// REPLACE {{#if class}} with {% if class %}
var regex = /\{\{#if\s+([a-zA-Z0-9-_\.]+)?\}\}/gi;
var replaceVal = '{% if $1 %}';
var newContent = oldContent.replace(regex, replaceVal);
// REPLACE {{/if}} with {% endif %}
oldContent = newContent;
regex = /\{\{\/if\}\}/gi;
replaceVal = '{% endif %}';
newContent = oldContent.replace(regex, replaceVal);
/* REPLACE
{{> social-list
dark="true"
centered="true"}}
with
{% set dark="true" %}
{% set centered="true" %}
{% include social-list.njk %} */
function replacer(match, p1, p2, offset, string) {
var variablesArray = p2.split(/"\s+/gi);
variablesArray = variablesArray.filter(n => n);
var statements = variablesArray.map(function (statement) {
return `{% set ${statement}" %}`;
});
statements = statements.join("\n") + "\n" + `{% include "${p1}.njk" %}`;
return statements;
}
oldContent = newContent;
regex = /\{\{>\s*([a-zA-Z0-9-_/]+)?\s*([a-zA-Z0-9-_/\.=:"'\s]+)\s*\}\}/gi;
newContent = oldContent.replace(regex, replacer);
fs.writeFileSync(filePath, newContent, {encoding: 'utf-8'});
console.log(`Edited file: ${filePath}`);
}
};
const main = () => {
const dir = 'temp'; // folder name containing files
const filePaths = walk(dir);
filePaths.forEach(filePath => edit(filePath));
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment