Trigger TagHelper from another TagHelper

落爺英雄遲暮 提交于 2019-12-11 06:03:50

问题


I would like to trigger the stock ScriptTagHelper (view source on GitHub) so that it would emulate the asp-append-version="true" attribute.

I know that the proper way to use this is to just change from this:

<script src="somefile.js"></script>

to this:

<script src="somefile.js" asp-append-version="true"></script>

This process is very similar for versioning CSS includes and images (LinkTagHelper and ImageTagHelper).

Since I have a lot of included scripts, stylesheets, and images, I would like to automate things a bit. So instead of adding asp-append-version="true" on each and every HTML element, I would rather create a custom TagHelper that does this for me.

Herein lies the problem - it does not work.

Currently, my TagHelper covers only script tags and looks like this:

  [HtmlTargetElement("script", Attributes = "src")]      
  public class TestTagHelper : TagHelper
  {
    public override int Order => int.MinValue;
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
      if(!context.AllAttributes.ContainsName("asp-append-version"))
      {
        output.Attributes.SetAttribute("asp-append-version", "true");
      }
    }
  }

But instead of triggering the default ScriptTagHelper, it literally outputs the asp-append-version="true" to the output HTML. I have also set the Order property to INT_MIN, so that it fires before any other Tag Helpers, but it still doesn't work.

Is there a way to make this work?


回答1:


As @ChrisPratt mentioned, chaining TagHelpers is not possible. There is a little, dirty trick which might help you out. You could new up an instance of ScriptTagHelper manually in your own tag helper and invoke the Process method manually:

[HtmlTargetElement("script", Attributes = "src")]
public class TestTagHelper : TagHelper
{
    public override int Order => int.MinValue;

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (!context.AllAttributes.ContainsName("asp-append-version"))
        {
            var scriptTagHelper = new ScriptTagHelper(...) // Inject the required dependencies here
            {
                AppendVersion = true, // Explicitly set to true
                // Map all other properties
            };
            scriptTagHelper.Process(context, output);
        }
    }
}


来源:https://stackoverflow.com/questions/50857188/trigger-taghelper-from-another-taghelper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!