How to render scripts, generated in TagHelper process method, to the bottom of the page rather than next to the tag element?

后端 未结 7 1415
情深已故
情深已故 2020-12-11 06:28

I am generating scripts in process method of TagHelper class as follows

[TargetElement(\"MyTag\")]
    public Class MYClass: TagHelper{
      public override         


        
7条回答
  •  感情败类
    2020-12-11 07:22

    Create a BodyTagHelper which inserts a value into TagHelperContext.Items and is then set in your custom TagHelper.

    Full bit of code:

    public class BodyContext
    {
        public bool AddCustomScriptTag { get; set; }
    }
    
    public class BodyTagHelper : TagHelper
    {
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var builder = new StringBuilder();
    
            var bodyContext = new BodyContext();
    
            context.Items["BodyContext"] = bodyContext;
    
            // Execute children, they can read the BodyContext
            await context.GetChildContentAsync();
    
            if (bodyContext.AddCustomScriptTag)
            {
                // Add script tags after the body content but before end tag.
                output
                    .PostContent
                    .Append("");
            }
        }
    }
    
    [TargetElement("MyTag")]
    public class MYClass : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            // Do whatever you want
    
            object bodyContextObj;
            if (context.Items.TryGetValue("BodyContext", out bodyContextObj))
            {
                // Notify parent that we need the script tag
                ((BodyContext)bodyContextObj).AddCustomScriptTag = true;
            }
        }
    }
    

    Hope this helps!

提交回复
热议问题