Created
February 1, 2022 19:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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