wenzeslaus
wenzeslaus

Reputation: 717

How to specify language when using highlight.js?

I'm using highlight.js to highlight code blocks in HTML. highlight.js can find all code blocks and determine the language automatically but I would like to specify both element(s) and language(s) manually. By specifying the language I would like to avoid overhead of determining which language it is (although highlight.js is fast, it could be faster if it would skip the language detection, I guess).

In HTML I specify the language as a class (I need this for some styling of the code block).

<pre>
<code class="python">
print "Hello"
</code>
</pre>

In JavaScript I iterate over the code elements (for some other reason I need to get a list of these elements). When I'm iterating over the code elements, I call hljs.highlightBlock function. Because I know the language (stored as class), I think it would be advantageous to actually tell highlight.js the language it should highlight.

From the usage examples on highlight.js web site I guessed that I can call hljs.configure function and specify a list of languages to try:

// ...
if (codeElement.hasClass('python'))
    language = 'python';
else if (codeElement.hasClass('bash'))
    language = 'bash';

hljs.configure({languages: [language]});
hljs.highlightBlock(codeElement[0]);

However, I'm not sure if this is the right way to do it. First, it is not clear to me if this is an official API I can rely on. Second, I think that highlight.js is still trying to determine if the code block is in the given language or not (which is what I wanted to avoid in the first place).

Upvotes: 11

Views: 11047

Answers (2)

Sylvester Das
Sylvester Das

Reputation: 194

As of 2023:

const highlightedCode = hljs.highlight('print "hello"', { language: 'python' }).value

document.getElementById('code').innerHTML = `<code>${highlightedCode}</code>`
pre {
  font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas,
    Liberation Mono, monospace;
  background-color: #f6f8fa;
  padding: 1rem;
}

code {
  white-space: break-spaces;
  border-radius: 6px;
  word-break: normal;
  white-space: pre;
  border: 0;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<pre id="code"></pre>

Upvotes: 1

Max
Max

Reputation: 316

You are iterating over 'pre code' elements right? But you specified the language in the 'code' tag instead of the 'pre' tag. I had the same problem and specifiyng the language on the topmost element fixed the issue. Your html code should look like this:

<pre class="python">
<code>
print "Hello"
</code>
</pre>

Also make sure that 'python' is included in the highlight.js pack that you are using :)

Upvotes: 9

Related Questions