Razor TagHelper Method for Transforming Markdown into HTML

  • 2021-10-15 10:24:46
  • OfStack

Markdown is a markup language that can be written with a plain text editor. With a simple markup syntax, it can make plain text content have a definite format.

Use

The syntax of Markdown is concise, easy to learn, and more powerful than plain text, so many people use it to write blogs. The world's most popular blog platform WordPress and large CMS such as Joomla, Drupal can support Markdown well. Blog platforms that fully adopt Markdown editors include Ghost and Typecho.

Used to write a description document and saved under the directory of the software under the file name "README. MD".

In addition, now that we have a God-level editor like RStudio, we can quickly convert Markdown into speeches PPT, Word product documents, LaTex papers and even complete the smallest available prototypes with a very small amount of code. In the field of data science, Markdown has been established as a scientific research norm, which greatly promotes the historical process of dynamic repeatability research.

TagHelper

Write an Razor TagHelper to implement Markdown to HTML, here need to use CommonMark. NET this class library.


namespace ZKEACMS.Message.TagHelps
{
 [HtmlTargetElement("markdown", TagStructure = TagStructure.NormalOrSelfClosing)]
 [HtmlTargetElement(Attributes = "markdown")]
 public class MarkdownTagHelper : TagHelper
 {
  public ModelExpression Content { get; set; }
  public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
  {
   if (output.TagName == "markdown")
   {
    output.TagName = null;
   }
   output.Attributes.RemoveAll("markdown");
   var content = await GetContent(output);
   var markdown = WebUtility.HtmlEncode(WebUtility.HtmlDecode(content));
   var html = CommonMarkConverter.Convert(markdown);
   output.Content.SetHtmlContent(html ?? "");
  }
  private async Task GetContent(TagHelperOutput output)
  {
   if (Content == null)
    return (await output.GetChildContentAsync()).GetContent();
   return Content.Model?.ToString();
  }
 }
}

Usage

First, add this TagHelper to _ ViewImports. cshtml, like this


@addTagHelper *, ZKEACMS.Message

Then you can use it directly


<markdown>@item.CommentContent</markdown>

Related articles: