Last active
January 27, 2021 15:44
-
-
Save OldBigBuddha/0aec514c797bbcb1d5924442ca7b4f6d to your computer and use it in GitHub Desktop.
Nunjucks Custom Tag
This file contains hidden or 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
| // Ref 1: https://mozilla.github.io/nunjucks/api.html#custom-tags | |
| // Ref 2: https://dreamonward.com/2019/12/05/nunjucks-custom-tag/ | |
| const nunjucks = require("nunjucks") | |
| const DATA = "# Header 1\n\n{% test %}\nHere is Test Section\n{% endtest %}" | |
| class CustomTag { | |
| constructor() { | |
| this.tags = ["test"] | |
| } | |
| parse(parser, nodes) { | |
| const token = parser.nextToken(); // Get the tag token | |
| // Parse the args and move after the block end. | |
| const args = parser.parseSignature(null, true); | |
| parser.advanceAfterBlockEnd(token.value); | |
| // Parse the body | |
| const body = parser.parseUntilBlocks('test', 'endtest'); | |
| parser.advanceAfterBlockEnd(); | |
| // Actually do work on block body and arguments | |
| return new nodes.CallExtension(this, 'run', args, [body]); | |
| }; | |
| run(context, bodyCallback) { | |
| const body = bodyCallback() | |
| const html = `<p>${body}</p>` | |
| return new nunjucks.runtime.SafeString(html) | |
| } | |
| } | |
| const env = new nunjucks.Environment() | |
| env.addExtension("test", new CustomTag()) | |
| console.log(env.renderString(DATA, null)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment