I am generating scripts in process method of TagHelper class as follows
[TargetElement(\"MyTag\")]
public Class MYClass: TagHelper{
public override
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!