In this new post, I show you how to add code snippet in Razor pages for Blazor WebAssembly and Blazor Server. In the last few weeks, I’m on fire with Blazor! I love it! So, I created a Blazor component that is based on highlight.js.
So, the goal of this new component is to help us to add in a Razor page a piece of code and color it with the color convention for the language using different style. For example, I want to display a code from C# using the Visual Studio style. The result is like the following screenshot

Also, I want to add dynamically the required scripts and the CSS based on the language and the style I like to display. For adding dynamically scripts and CSS, few days ago I created a post where I exactly explain how to do that (coincidence?)
As usual, you have the full source code of this component on GitHub but please leave your comment at the bottom of this post or in the forum in the section CodeSnippet for Blazor. Also, you can download a NuGet package.
Usage
In your Index.html
or _Host
add this line
<script src="/_content/PSC.Blazor.Components.CodeSnippet/codesnippet.js"></script>
Then, in your _Imports.razor
add this line
@using PSC.Blazor.Components.CodeSnippet
Based on the parameters, the component adds automatically the required scripts and CSS in your page.
Add a CodeSnippet
For example, I want to add a C# code with the *Visual Studio Style. Between the CodeSnippet
tag, you have to add the code you want to show. This is the code.
<CodeSnippet Language="Language.csharp" Style="Style.VisualStudio">
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await _js.InvokeVoidAsync("loadJs", targetUrl);
}
</CodeSnippet>
Then, I want to add a new CodeSnippet using XML and the style of Android Studio. You have to replace special characters like < (<) with the corrispondent HTML code. If you have multiple CodeSnippet
in the same pag, you can avoid to load multiple times the highlight.js
setting to false
the parameter LoadMainScript
.
<CodeSnippet Language="Language.xml" Style="Style.AndroidStudio" LoadMainScript="false">
<CodeSnippet Language="Language.xml">
</CodeSnippet>
</CodeSnippet>
As a note, because this component is using highlight.js, you can choose between 196 programming languages with 243 styles! See the list of the full languages and styles on GitHub.
Wrap up
In conclusion, add Code Snippet in Razor pages is very straight forward with my new component. Please leave your comment at the bottom of this post or in the forum in the section CodeSnippet for Blazor.