Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling TagHelpers from another TagHelper?

Is there any way to get a TagHelper to render another TagHelper?

Example TagHelpers;

public class OuterTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "";
        output.Content.SetContent("Hello <inner></inner>");
    }
}

public class InnerTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "";
        output.Content.SetContent("World!");
    }
}

Example View;

<outer></outer>

Expected Result;

Hello World!

I know I probably should use a ViewComponent instead, but is it at all possible to achieve the expected behavior presented above?

like image 615
jovnas Avatar asked Sep 21 '15 10:09

jovnas


1 Answers

If you need to use some of the existing tag helper type functionality then you can access it from IHtmlGenerator. This won't help to access custom tag helper functionality but if you just need the functionality of existing stuff like label, input then this will work

[HtmlTargetElement("input", Attributes = nameof(Wrap) + ", asp-for")]
[HtmlTargetElement("select", Attributes = nameof(Wrap) + ", asp-for")]
public class FormGroupWrapperTagHelper : TagHelper
{
    public FormGroupWrapperTagHelper(IHtmlGenerator generator)
    {
        Generator = generator;
    }

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    protected IHtmlGenerator Generator { get; }

    public ModelExpression AspFor { get; set; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var generateValidationMessage = Generator.GenerateValidationMessage(ViewContext,
                                                                  AspFor.Name,
                                                                  message: null,
                                                                  tag: null,
                                                                  htmlAttributes: null);
.....
}
like image 118
GraemeMiller Avatar answered Sep 17 '22 23:09

GraemeMiller