Skip to content

Instantly share code, notes, and snippets.

@MichaelSolati
Created February 1, 2022 19:49
Show Gist options
  • Save MichaelSolati/16584a883ec67854b9421dc51b186bd6 to your computer and use it in GitHub Desktop.
Save MichaelSolati/16584a883ec67854b9421dc51b186bd6 to your computer and use it in GitHub Desktop.
Takes an 11ty shortcode and lets you load it as a NJK extension
/**
* Takes any 11ty shortcode that takes an argument and converts
* it into a NJK extension.
*
* @param {string} name The name of the extension/shortcode
* @param {(...args: any[]) => any} func The code to execute
* @returns {import('nunjucks').Extension} A NJK extension
*/
module.exports = function createNJKExtension(name, func) {
/** @type {import('nunjucks').Extension} */
class Extension {
constructor() {
this.tags = [name];
}
parse(parser, nodes) {
const tok = parser.nextToken();
const args = parser.parseSignature(null, true);
parser.advanceAfterBlockEnd(tok.value);
return new nodes.CallExtension(this, 'run', args, null);
}
run(_, data = {}) {
return func(data);
}
}
return new Extension();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment