Skip to content

Instantly share code, notes, and snippets.

Created December 5, 2019 15:22
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Nunjuck highlight.js tag extension
// Allows highlighting of code blocks in Nunjucks template.
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);
// Parse the body
const body = parser.parseUntilBlocks('highlightjs', 'endhighlightjs');
// Actually do work on block body and arguments
return new nodes.CallExtension(this, 'run', args, [body]);
}; = 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());
Copy link

how to use?

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