Using Blazor and Code Highlight

Code highlight or syntax highlight is a feature that displays text as source code. It is using different fonts and colors, that matches with the syntactical meaning of the code constructs. For examples keywords such as public or if are colored blue, while method names such as Main() can be colored to green. Highlighting code on an HTML website is a relatively easy task if one is using an existing syntax highlighter.

Integrating an existing code highlighter with Blazor is a one step more complex though. In this post, I am going integrate a Blazor site with Prism, which is a lightweight extensible code highlighter.

Getting started

The first step with prism is to choose a theme, additional languages and plugins. Prism will generate a CSS file and a Javascript file, which can be downlaoded from their website. Both files then should be added to the wwwroot folder of the Blazor project.

Optionally we can use a CDN to host these files, or to re-use a well-known stylesheet and JS script file.

To get started, the suggestion is to reference both files on html page. In case a Blazor application this can be the _Hosts.cshtml on the server side or the index.html in a client side, WebAssembly based application.

<link rel="stylesheet" href="css/prism.css" />
...
<script src="js/prism.js"></script>

Prism's javascript subscribes to the DOMContentLoaded event, and using the CSS file, it will highlight code in the DOM placed inside code elements: <pre><code class="language-csharp">public void Main() { }</code></pre>.

public void Main() { }

The Blazor bit

At this point, one testing the application realizes, that code highlighting is not working as expected. This is because how the Blazor application updates the DOM. The <code> elements might be added to the DOM after the DOMContentLoaded event fired. So that changes made to the DOM later are processed by Prism, we need to tell Prism when to start highlighting. To do this will need JSInterop inside the Blazor application.

First, using the built in Dependency Injection container, we need to ask for a IJSRuntime dependency to be injected in the page using the code highlight:

@inject IJSRuntime _jsRuntime

Secondly, call Prism.highlightAll JS function in the OnAfterRenderAsync C# method, which is invoked by the Blazor runtime, when the rendering of the page completes.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await _jsRuntime.InvokeVoidAsync("Prism.highlightAll");
}

With all these changes now, we may re-test our application, and code highlighting should be on similar to regular HTML applications.

Final Thoughts

In a production application, consider using the minified and bundled versions of the referenced CSS and JS files.

Consider setting data-manual attribute on the <script> element to avoid the first iteration of code highlighting.