0

我已经构建了两打 HTML 帮助程序,我将其转换为 ASP.NET 5 MVC 6 的标记帮助程序,以生成 Facebook Open Graph 元标记。这是“网站”类型的示例:

索引.cshtml

<open-graph-website title="Page Title" 
                    main-image="new OpenGraphImage(
                        "~/img/open-graph-1200x630.png", 
                        "image/png", 
                        1200, 
                        630)"
                  determiner="Blank"
                  site-name="Site Title">

每个 Open Graph 对象类型都有一个特殊的命名空间,必须将其添加到 head 标签中,例如

_Layout.cshtml

<html>
<head prefix="website: http://ogp.me/ns/website#">
</head>
<body>
    <!-- ...Omitted -->
</body>
</html>

Namespace过去,我通过使用 ViewBag 和类上的 getter 属性设法使用 HTML Helpers 做到这一点,OpenGraphWebsite如下所示:

索引.cshtml

ViewBag.OpenGraph = new OpenGraphWebsite(
    "Page Title",
    new OpenGraphImage("/img/open-graph-1200x630.png", "image/png", 1200, 630)
    {
        Determiner = OpenGraphDeterminer.Blank,
        SiteName = "Site Title"
    };

_Layout.cshtml

<html>
<head @(ViewBag.OpenGraph == null ? null : ViewBag.OpenGraph.Namespace)>
    @Html.OpenGraph((OpenGraphMetadata)ViewBag.OpenGraph);
</head>
<body>
    <!-- ...Omitted -->
</body>
</html>

有没有办法使用标签助手实现类似的结果?命名标签助手或引用它的某种方式?

4

2 回答 2

1

看起来这在相应的 GitHub问题中得到了讨论/回答。

于 2015-10-01T17:45:13.803 回答
0

这是我在GitHub 上提出的问题的答案。请注意,此标签助手会自动运行,因为它只针对 head 元素。

[TargetElement("open-graph-website", Attributes = nameof(Title) + "," + nameof(MainImage), TagStructure = TagStructure.WithoutEndTag)]
public class OpenGraphWebsiteTagHelper : OpenGraphMetadataTagHelper // Inherits from TagHelper
{
    // ... Omitted
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        context.Items[typeof(OpenGraphMetadata)] = this.GetNamespaces();
        output.Content.SetContent(this.ToString());
    }
}

[TargetElement("head")]
public class OpenGraphNamespacePrefixTagHelper : TagHelper
{
     private const string PrefixAttributeName = "prefix";

    public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        context.Items.Add(typeof(OpenGraphMetadata), null);

        await context.GetChildContentAsync();

        string namespaces = context.Items[typeof(OpenGraphMetadata)] as string;
        if (namespaces != null)
        {
            output.Attributes.Add(PrefixAttributeName, namespaces);
        }
    }
}

我仍然会尝试添加一个虚拟的必需属性。这将迫使用户选择使用标签助手,而不是仅仅因为他们添加了标签助手 DLL 而自动运行。如果可以将无值属性添加到标签助手以促进布尔属性的此功能,那就太好了:

<head asp-open-graph-prefix>
Rather than:
<head asp-open-graph-prefix="true">

[TargetElement("head", Attributes = OpenGraphPrefixAttributeName)]
public class OpenGraphNamespacePrefixTagHelper : TagHelper
{
    private const string OpenGraphPrefixAttributeName = "asp-open-graph-prefix";

    [HtmlAttributeName(OpenGraphPrefixAttributeName)]
    public bool DUMMY { get; set; }

    // ..Omitted
}
于 2015-10-02T06:32:04.030 回答