Markdown extensions

Run a Markdig pipeline in a processor and in your pages, with alerts, custom containers and your own extensions.

On this page
Data/Markdown/BlogMarkdown.cscsharp
private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder()
    .UseAdvancedExtensions()
    .UseAutoIdentifiers(AutoIdentifierOptions.GitHub)
    .Build();

Bevel does not render Markdown. It gives you the body as RawMarkdown, and you choose the renderer. Most sites use Markdig. You build one pipeline and use it in two places: in a processor at build time, and in a component when the page renders.

One pipeline, shared

The sample blog keeps the pipeline in one service. A processor and a Razor component both use it.

samples/Bevel.SampleBlog/Data/Markdown/BlogMarkdown.cscsharp
private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder()
    .UseAdvancedExtensions()
    .UseAutoIdentifiers(AutoIdentifierOptions.GitHub)
    .Build();

The service sits in Data/, so the build-time data step compiles it. Register it in the build-time services too:

Data/DataStartup.cscsharp
public sealed class DataStartup : IBevelDataStartup
{
    public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        services.AddBlogServices(configuration);
    }
}

AddBlogServices is the shared method. It registers IBlogMarkdown, and Program.cs calls it for the running app. See BlogServices.cs.

Use it in a processor

A processor takes the service in its constructor. It reads RawMarkdown and fills members at build time.

Data/Posts/PostProcessors.cscsharp
public sealed class PostStats(IBlogMarkdown markdown, IReadingTimeCalculator time) : IProcessor<BlogPost>
{
    public ProcessResult<BlogPost> Process(BlogPost post)
    {
        var words = markdown.CountWords(post.RawMarkdown);
        return post with { WordCount = words, ReadingMinutes = time.Minutes(words) };
    }
}

The data step cannot see your Razor or the generated ISiteData, so keep this code under Data/.

Use it in a page

The Markdown component renders RawMarkdown. It parses once and shares the result with the table of contents, so heading ids always match.

Components/Markdown.razorrazor
<div class="prose">
  @((MarkupString)_rendered.Html)
</div>

@code {
  [Parameter] public string Content { get; set; } = string.Empty;

  private RenderedMarkdown _rendered = default!;

  protected override void OnParametersSet() => _rendered = Renderer.Render(Content);
}

Alerts

Markdig can turn > [!NOTE] blocks into alert blocks. Add the extension to the builder.

csharp
var pipeline = new MarkdownPipelineBuilder()
    .UseAdvancedExtensions()
    .UseAlertBlocks()
    .Build();

You write an alert in Markdown like this:

markdown
> [!TIP]
> Run `dotnet watch` to see edits as you type.

The five kinds are NOTE, TIP, IMPORTANT, WARNING and CAUTION. This site renders them as <aside class="alert alert--tip"> with an icon, and fails the build on any other kind (DOCS010).

Custom containers

UseCustomContainers() reads ::: name blocks. This site uses them for steps, cards and tabs.

csharp
var pipeline = new MarkdownPipelineBuilder()
    .UseAdvancedExtensions()
    .UseCustomContainers()
    .Build();
markdown
::: steps
### Install the template
Run `dotnet new install Bevel.Templates`.
:::

Markdig gives you a CustomContainer block with Info set to steps. You decide what HTML it becomes.

Write your own extension

This site finds extensions by reflection. Each one is a class with a parameterless constructor that implements IDocsMarkdownExtension.

Data/Markdown/Extensions/StepsExtension.cscsharp
public sealed class StepsExtension : IDocsMarkdownExtension
{
    public int Order => 20;                                   // lower runs first
    public void Setup(MarkdownPipelineBuilder pipeline) { }   // register parsers
    public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) { }  // register HTML renderers
    public void Process(MarkdownDocument document, DocsRenderContext context) { }  // optional pass over the parsed tree
}

Process runs after parsing and before heading ids. Use it to rewrite blocks, resolve cross-references, read repo files and report problems with context.Error(code, message, line). The build then fails with the file and line.

The sources are in Data/Markdown/Extensions. Start with AlertExtension.cs and StepsExtension.cs.

Report problems from Markdown processing

A processor that takes BevelLoadContext can report diagnostics with your own code. They print as file(line,col): error CODE: message. Any error fails the build after every dataset has loaded, so you see all of them at once. This is how this site fails on a broken cross-reference.

csharp
public sealed class LinkCheck(BevelLoadContext ctx) : IDatasetProcessor<Page>
{
    public IReadOnlyList<Page> Process(IReadOnlyList<Page> items)
    {
        // ctx.ReportError("DOCS033", "Unresolved xref.", file: "Data/Docs/x.md", line: 12);
        return items;
    }
}