Repository navigation
Expand file tree
/
Copy pathMarkdownTagHelper.cs
More file actions
92 lines (79 loc) · 3.13 KB
/
Copy pathMarkdownTagHelper.cs
File metadata and controls
92 lines (79 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// run node postinstall.js to update to latest version
using Markdig;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace MyApp;
[HtmlTargetElement("markdown", TagStructure = TagStructure.NormalOrSelfClosing)]
[HtmlTargetElement(Attributes = "markdown")]
public class MarkdownTagHelper : TagHelper
{
public ModelExpression? Content { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (output.TagName == "markdown")
{
output.TagName = null;
}
output.Attributes.RemoveAll("markdown");
var content = await GetContent(output);
var pipeline = new MarkdownPipelineBuilder()
.UseAdvancedExtensions()
.Build();
var writer = new StringWriter();
var cls = output.Attributes["class"]?.Value ?? "prose";
await writer.WriteAsync($"<div class=\"{cls}\">");
var renderer = new Markdig.Renderers.HtmlRenderer(writer);
pipeline.Setup(renderer);
var include = output.Attributes["include"]?.Value?.ToString() ?? "";
if (!string.IsNullOrEmpty(include))
{
MarkdownFileBase? doc = null;
if (include.EndsWith(".md"))
{
var includes = HostContext.TryResolve<MarkdownIncludes>();
var pages = HostContext.TryResolve<MarkdownPages>();
// default relative path to _includes/
include = include[0] != '/'
? "_includes/" + include
: include.TrimStart('/');
doc = includes.Pages.FirstOrDefault(x => x.Path == include);
if (doc == null && pages != null)
{
var prefix = include.LeftPart('/');
var slug = include.LeftPart('.');
var allIncludes = pages.GetVisiblePages(prefix, allDirectories: true);
doc = allIncludes.FirstOrDefault(x => x.Slug == slug);
}
if (doc?.Preview != null)
{
renderer.WriteLine(doc.Preview!);
}
else
{
var log = HostContext.Resolve<ILogger<IncludeContainerInlineRenderer>>();
log.LogError("Could not find: {Include}", include);
renderer.WriteLine($"Could not find: {include}");
}
}
else
{
renderer.WriteLine($"Could not find: {include}");
}
}
else
{
var document = Markdown.Parse(content ?? "", pipeline);
renderer.Render(document);
}
await writer.WriteAsync("</div>");
await writer.FlushAsync();
var html = writer.ToString();
output.Content.SetHtmlContent(html ?? "");
}
private async Task<string?> GetContent(TagHelperOutput output)
{
if (Content == null)
return (await output.GetChildContentAsync()).GetContent();
return Content.Model?.ToString();
}
}