Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Nunjuck highlight.js tag extension
//
// 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
You can’t perform that action at this time.