.netdotnetnukemarkupreadmemarkdig

Markup file slug in .NET


I am using Markdig nuget package right now to read my markup files and convert them to HTML

 string content = File.ReadAllText(mdFilepath);

 string? result = Markdown.ToHtml(content, pipeline);

But now I have added following lines to start of each blog :

---
title: 'This is the title of the blog'
description: 'Dummy description'
pubDate: 'Feb 11 2023'
coverImage: './blogs/covers/blog1.png'
---

This is blog, lorem ipsum ......
More content....

Additionally these lines in --- tags are not being read by File.ReadAllText method.

How can I create/use some sort of slug or a convertor/reader that I should get above details in a different model.


Solution

  • To read that block (which internally is YAML).

    1. Add YAML front matter support to Markdig's parser by calling UseYamlFrontMatter() when building the parser pipeline.

    2. When you have the AST from MarkdownParser.Parse(markdownContent, markdownPipeline) you can find the first YamlFrontMatterBlock

      if (ast.FirstOrDefault(blk => blk is YamlFrontMatterBlock) is YamlFrontMatterBlock yb) {
         // yb is the front matter
      }
      
    3. You'll need a YAML parser (I've used YamlDotNet previously):

      var yanl = yb.Lines.ToString();
      var information = yamlDeserialiser.Deserialize<MarkdownFrontMatter>(yaml);
      

    Where MarkdownFrontMatter is a type with the set of properties to extract (using nullable string properties to avoid problems should a property not have a value).

    NB using

    var html = Markdown.ToHtml(content, pipeline);
    

    is just a short cut for:

    var mdAst = MarkdownParser.Parse(content, pipeline);
    var html = mdAst.ToHtml(pipeline);