Skip to content

Instantly share code, notes, and snippets.

@RRMoelker
Created December 5, 2019 15:22
Show Gist options
  • Save RRMoelker/05376936757a19c4848bea908d41bac2 to your computer and use it in GitHub Desktop.
Save RRMoelker/05376936757a19c4848bea908d41bac2 to your computer and use it in GitHub Desktop.
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());
@dimaslanjaka
Copy link

how to use?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment