Created
December 5, 2019 15:22
-
-
Save RRMoelker/05376936757a19c4848bea908d41bac2 to your computer and use it in GitHub Desktop.
Nunjuck highlight.js tag 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
// | |
// Allows highlighting of code blocks in Nunjucks template. | |
// https://mozilla.github.io/nunjucks/api.html#custom-tags | |
// | |
const nunjucks = require('nunjucks'); | |
const hljs = require('highlight.js'); | |
function HighlightJsExtension() { | |
this.tags = ['highlightjs']; | |
this.parse = function (parser, nodes) { | |
const tok = parser.nextToken(); // Get the tag token | |
// Parse the args and move after the block end. | |
const args = parser.parseSignature(null, true); | |
parser.advanceAfterBlockEnd(tok.value); | |
// Parse the body | |
const body = parser.parseUntilBlocks('highlightjs', 'endhighlightjs'); | |
parser.advanceAfterBlockEnd(); | |
// Actually do work on block body and arguments | |
return new nodes.CallExtension(this, 'run', args, [body]); | |
}; | |
this.run = function (context, language, bodyCallback) { | |
const rawCode = bodyCallback(); | |
const code = hljs.highlightAuto(rawCode, [language]); | |
const html = `<pre><code class="hljs language-${language.toLowerCase()}">${code.value}</code></pre>`; | |
return new nunjucks.runtime.SafeString(html); | |
}; | |
} | |
const TEMPLATE_DIR = './template/'; | |
const templateLoader = new nunjucks.FileSystemLoader(TEMPLATE_DIR); | |
const env = new nunjucks.Environment(templateLoader); | |
env.addExtension('HighlightJsExtension', new HighlightJsExtension()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to use?