"About the "代码" tag in the RichText field of "内容丰富的 dotnet SDK


Contentful中的RichText被反序列化为Document类型,Document被转换为MarkupString类型以供使用。(我创建了一个扩展方法(。当使用";代码";在Contentful的RichTextEditor中;预";标记在父元素中不存在,因此浏览器将忽略换行符和缩进。

有没有一种方法可以将父元素添加到任何HTML标记中?

public static MarkupString ToHtml(this Document doc)
{
var renderer = new HtmlRenderer();
var html = renderer.ToHtml(doc).GetAwaiter().GetResult();
return (MarkupString)html;
}

使用Blazor ServerSide。

<div>
@entry.Content.ToHtml()
</div>

型号

public class ContentfulEntry
{
public SystemProperties Sys { get; set; }
public string Title { get; set; }
public Document Content { get; set; }
public string Description { get; set; }
public Asset Cover { get; set; }
}

为Text:实现自定义渲染器

public class CustomTextRenderer : IContentRenderer
{
/// <summary>
/// The order of this renderer in the collection.
/// </summary>
public int Order { get; set; } = 90;
/// <summary>
/// Whether or not this renderer supports the provided content.
/// </summary>
/// <param name="content">The content to evaluate.</param>
/// <returns>Returns true if the content is a textual node, otherwise false.</returns>
public bool SupportsContent(IContent content)
{
return content is Text;
}
/// <summary>
/// Renders the content to a string.
/// </summary>
/// <param name="content">The content to render.</param>
/// <returns>The content as a string.</returns>
public string Render(IContent content)
{
var text = content as Text;
var sb = new StringBuilder();
if (text.Marks != null)
{
foreach (var mark in text.Marks)
{
if(mark == "code">) {
sb.Append("<pre>");                    
}
sb.Append($"<{MarkToHtmlTag(mark)}>");
}
}
sb.Append(text.Value);
if (text.Marks != null)
{
foreach (var mark in text.Marks)
{
sb.Append($"</{MarkToHtmlTag(mark)}>");
if(mark == "code">) {
sb.Append("</pre>");                    
}
}
}
return sb.ToString();
}
private string MarkToHtmlTag(Mark mark)
{
switch (mark.Type)
{
case "bold":
return "strong";
case "underline":
return "u";
case "italic":
return "em";
case "code":
return "code";
}
return "span";
}
/// <summary>
/// Renders the content asynchronously.
/// </summary>
/// <param name="content">The content to render.</param>
/// <returns>The rendered string.</returns>
public Task<string> RenderAsync(IContent content)
{
return Task.FromResult(Render(content));
}
}

然后将其添加到HTML渲染器的渲染器集合中:

public static MarkupString ToHtml(this Document doc)
{
var renderer = new HtmlRenderer();
renderer.AddRenderer(new CustomTextRenderer());
var html = renderer.ToHtml(doc).GetAwaiter().GetResult();
return (MarkupString)html;
}

请注意,Order属性控制渲染器的求值顺序。这意味着此自定义渲染器将在默认渲染器之前进行评估。

相关内容

  • 没有找到相关文章

最新更新