Tags:

Syntax highlight code snippets in Episerver - Part 3: Display language label

Step 1: Add a language label

I would like to display the name of the programming language in the top right corner, like this.

A code snippet with a label in the top right corner: C#

One problem with this is, that I do not want to add any extra markup. I want to use the unmodified Code Sample plugin, I want to be able to change or reposition the label, and I want to be able to switch out Highlight.js with another syntax highlighter in the future.

I accomplish this with the following JavaScript and insertAdjacentHTML.

addEventListener('load',
   function () {
      var blocks = document.querySelectorAll('pre code.hljs');
      Array.prototype.forEach.call(blocks,
         function (block) {
            var language = block.result.language;
                
            if (language ) {
               block.insertAdjacentHTML("afterbegin", "<label>"
                  + language
                  + "</label>");
            }
         });
  });

Step 2: Formatting the language name

This works, but it will show the language code from Highlight.js, i.e. csharp instead of C#. I want full control over the display name, so I add some final logic.

addEventListener('load',
   function () {
      var blocks = document.querySelectorAll('pre code.hljs');
      Array.prototype.forEach.call(blocks,
         function (block) {
            var language = block.result.language;
            var formattedLanguage;
            switch (language) {
               case 'csharp':
                  formattedLanguage = 'C#';
                  break;
               case 'javascript':
                  formattedLanguage = 'JavaScript';
                  break;
               case 'razor':
                  formattedLanguage = 'Razor view';
                  break;
               case 'xhtml':
                  formattedLanguage = 'WebForms';
                  break;
               case 'css':
               case 'html':
               case 'json':
               case 'sql':
               case 'xml':
               case 'yaml':
                  formattedLanguage = language.toUpperCase();
                  break;
               default:
                  formattedLanguage = null;
                  break;
           }

           if (formattedLanguage) {
              block.insertAdjacentHTML("afterbegin", "<label>"
                 + formattedLanguage 
                 + "</label>");
           }
      });
   });

That's it!