How to specify language when using highlight.js?

Issue

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).

Solution

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 🙂

Answered By – Max

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.