Syntax highlighting for Blazor, based on highlight.js
Build | NuGet |
---|---|
You can install the package via the NuGet package manager just search for HighlightBlazor.
Add the following to your _Imports.razor
@using HighlightBlazor
Add the following line to the head
tag of your _Host.cshtml
(Blazor Server app) or index.html
(Blazor WebAssembly).
<link href="_content/HighlightBlazor/highlight-blazor-styles.css" rel="stylesheet">
<script src="_content/HighlightBlazor/highlight-blazor.js"></script>
These files include the js and default style of highlight.js.
You need to register the highlight services if you want to set the code style.
builder.Services.AddHighlight();
<pre>
<code>
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
</code>
</pre>
<CodeHighlight>
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
</CodeHighlight>
<CodeHighlight Indent="false">
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
</CodeHighlight>
<CodeHighlight Indent="true" CodeLanguage="json">
{
"success": true,
"data": [
{
"billCode": "BSTPU019524859",
"type": 1
}
]
}
</CodeHighlight>
<CodeHighlight>@SourceCode</CodeHighlight>
@code {
string SourceCode = @"
public class Aa
{
}
";
}
đź‘€NOTE:
<CodeHighlight>@SourceCode</CodeHighlight>
and<CodeHighlight> @SourceCode </CodeHighlight>
has different render effects. The second one causes more blanks and empty lines.
<CodeHighlight Code=@AnotherCode></CodeHighlight>
private void ChangeCode()
{
Random r = new Random();
AnotherCode = "public override void init_" + r.Next(0,100) + "()\n{\n Backend.Init();\n}";
}
Use Code=@AnotherCode
instead of <CodeHighlight>@AnotherCode</CodeHighlight>
, or it won't render immediately.
Same to highlight.js. See here.
You can set language by CodeLanguage
property, the default is empty, it means auto detect.
You can set different styles by HighlightService
.
@inject HighlightService highlightSrv
<div>
<input type="text" @bind-value="styleUrl" style="width:700px" />
</div>
<button class="btn btn-primary" @onclick="ApplyStyle">Apply Style</button>
@code {
private string styleUrl = "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/styles/a11y-dark.min.css";
private void ApplyStyle()
{
highlightSrv.SetStyleAsync(styleUrl);
}
}
Full supported styles list, you can see here.
By set Indent
to false
, it can display the origin code. Default is true
.