dotnet / dotnet/aspnetcore

TagHelper Extensions: .Prepend() and .WrapContent()

Open
#27,852 3 comments 3 reactions 0 assignees View on GitHub
affected-very-few area-mvc enhancement feature-mvc-razor-views severity-nice-to-have
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

Forgive me, as I am new to Razor TagHelpers.

When building a tag using a TagHelper, I'm finding myself often wanting to wrap the inner content of the component with an element, a `div.container` for example.

I've written this extension method, which wraps the tag content in a standard Bootstrap row.
```
public static void WrapContentInRow(this TagHelperOutput output)
{
output.PreContent.AppendHtml("

");
output.PostContent.AppendHtml("
");
}
```

The issue comes when I want to wrap the content in more than one element. The following code is an example of the outcome I want. The nav-dropdown-menu tag has two divs which are added by the TagHelper and are "wrapping" the content by prepending the starting tags and appending the ending tags.

Razor:
```

Label

Content

```

Becomes this raw html:
```


```

Currently, the way that I see to do this is to do the following (there may be some cleaner ways but I've boiled it down to this simple example):
```
output.PreContent.Append("

");
output.PostContent.Append("
");
```

This approach is OK, but it losses some of the benefit of the TagHelper. I would like to be able to do the following:
```
output.WrapContent(iHtmlContentObj);
```
or at least be able to create this extension method:
```
public static void WrapContent(this TagHelperOutput output, TagBuilder wrapper)
{
output.PreContent.PrependHtml(wrapper.RenderStartTag());
output.PostContent.AppendHtml(wrapper.RenderEndTag());
}
```

The extension method uses "PrependHtml()" which doesn't exist to my knowledge. With the implementation of this new method, one would be able to chain the wrapping of the content by multiple divs. Otherwise the ordering of closing or opening tags is incorrect.

The merit of `PrependHtml()` vs the merit of `WrapContent()` are separate IMO, and each should be considered on their own.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.