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.
_Host add this line
Then, in your
_Imports.razor add this line
Based on the parameters, the component adds automatically the required scripts and CSS in your page.
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);
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
<CodeSnippet Language="Language.xml" Style="Style.AndroidStudio" LoadMainScript="false">
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.