Felipe Costa Gualberto
Felipe Costa Gualberto

Reputation: 1117

Write content inside a custom tag helper

I wish that when I wrote the code below in razor:

<form-container>
    <h3>Hello World!</h3>
</form-container>

It renders into this:

<div class="row">
    <div class="col">

        <h3>Hello World!</h3>

    </div>
</div>

So far I began writing the tag helper class code for it, but I didn't manage to add child items into it:

public class FormContainerTagHelper : TagHelper {
    public override void Process(TagHelperContext context, TagHelperOutput output) {
        output.TagName = "div";
        output.TagMode = TagMode.StartTagAndEndTag;
        output.Attributes.Add("class", "row");

        //I wish I could do this:
        //output.Children.Add("div").Attributes.Add("class");
    }
}

Upvotes: 1

Views: 173

Answers (1)

Felipe Costa Gualberto
Felipe Costa Gualberto

Reputation: 1117

I was able to do it by using something like:

    output.PreContent.SetHtmlContent("<div class='col'>");
    output.PostContent.SetHtmlContent("</div>");

Upvotes: 1

Related Questions