前後にタグを出力するTagHelperを作ってみた - ASP.NET Core MVC

TagHelperを調べているとTagHelperOutputクラスに次のプロパティを見つけました。

このあたりのプロパティを使うと、タグの前後にタグを出力して例えばタグを入れ子にするといったこともできるようです。

ということでサンプルのTagHelperを作ってみました。(上記プロパティを試すのが目的で実用的なTagHelperではありません。)

public class SampleTagHelper : TagHelper {
    public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) {
        // 自身をpreタグに変換
        output.TagName = "pre";

        // 自身のpreタグにclass属性を設定
        output.Attributes.Add("class", "content");

        // preタグをdivタグで囲む
        output.PreElement.SetHtmlContent($"<div class=\"outer\">");
        output.PostElement.SetHtmlContent($"</div>");

        // コンテンツ(preタグの中)をcodeタグで囲む
        output.PreContent.SetHtmlContent($"<code class=\"inner\">");
        output.PostContent.SetHtmlContent($"</code>");

        return Task.CompletedTask;
    }
}

プロパティ名の"Element"はTagHelper自身のhtml要素のことで、"Content"はTagHelperのhtml要素の中身のことですね。

使ってみるとなんとなく想像した通りのhtmlを出力できました。

@* SampleTagHelperを使ってみる *@
<sample>
    <span>Content</span>
</sample>

@* 生成されるhtml(※わかりやすいように整形してあります) *@
<div class="outer">
    <pre class="content">
        <code class="inner">
            <span>Content</span>
        </code>
    </pre>
</div>
参考