Posted on

Display a Markdown file content in Balzor

You have for example many github repositories with well-done documentation and you want to use those files (*.md) in your own Blazor application? This is very simple. You only need to follow this article.

Introduction

To convert a DM file (a file with the .dm extension) to HTML in Blazor, you’ll need to use a library or tool that is capable of parsing the DM file and generating the corresponding HTML output.

One option is to use the Discord Markdown Parser library, which is a Python library that can parse DM files and generate HTML output. You can use this library by calling its API from your Blazor code using HttpClient.

Easy peasy…

If you want to simply display the content of your file, you can install and use the library Markdig.

Installation

You can install the package like this:

  • Nuget: NuGet\Install-Package Markdig
  • .NET CLI: dotnet add package Markdig

How to use?

Here’s an example of how you can use the Markdig library to convert a DM file to HTML in Blazor:

@page "/markdown"
@inject HttpClient Http

@MarkdownHtml

@code {
   
    private MarkupString MarkdownHtml { get; set; }

    protected async override Task OnInitializedAsync()
    {
        string markdown = await Http.GetStringAsync("MarkdownFile.md");
        MarkdownHtml = new MarkupString(Markdig.Markdown.ToHtml(markdown));
    }
}

For your info, I placed the file MarkdownFile.md in wwwroot in my Blazor WASM sample app. Here is the content of this file:

# My title
## My subtitle
 I am writing something here.

## Second subtitle
**Wow** this is _amazing_.

Oh I have a [link](https://mahdhi.com/) too!

And if you run your application, the result will be:

Displaying Markdown file content in Blazor

Conclusion

Keep in mind that this is just one way to convert a DM file to HTML in Blazor. There may be other libraries or tools that you can use for this purpose. If you know more about this subject ? Please share 😀

0Shares