I'm trying to use TagHelper
s to rewrite some of the meta
tags in my website.
For each meta
tag that has the following attributes: data-data-main,data-src
, I would like to replace the value of one of those attributes.
For example, this is the original:
<meta name="js" content="script" data-async="true" data-data-main="requirejs/product-overview/init" data-src="/js/libs/require.js">
I want to transform this into this:
<meta name="js" content="script" data-async="true" data-data-main="http://cdn.website.nl/8c87f33ca5acc7fdb9186d6a497642784685aabade058d3530bdf6d30168cfcd.js" data-src="/js/libs/require.js">
The only thing that changed is the data-data-main
attribute: it now points to an URL on the CDN instead of a local file.
I made a custom TagHelper
to help me achieve this goal:
[HtmlTargetElement("meta", Attributes = "[data-data-main],[data-src]")]
public class MetaScriptTagHelper : TagHelper
{
private readonly BluenotionSiteSettings _bnSiteSettings;
private readonly SiteTemplateService _templateService;
public MetaScriptTagHelper(BluenotionSiteSettingsFiller bnSiteSettingsFiller, SiteTemplateService templateService)
{
_bnSiteSettings = bnSiteSettingsFiller.Create(HttpContext);
_templateService = templateService;
}
[ViewContext]
public ViewContext ViewContext { get; set; }
private HttpContext HttpContext => ViewContext.HttpContext;
public override void Process(
TagHelperContext context, TagHelperOutput output)
{
var dataDataMainValue = context.AllAttributes["data-data-main"].Value.ToString();
var localPath = @".\wwwroot\js\" + dataDataMainValue.Replace('/', '\\') + ".js";
var siteTemplateId = _templateService.SiteTemplateBySiteIdAsync(_bnSiteSettings.SiteId);
var cdnPath = _templateService.GetResourceByName(siteTemplateId, localPath);
output.Attributes.Add("data-data-main", cdnPath);
}
}
Sadly, it returns an exception:
Found a malformed 'meta' tag helper. Tag helpers must have a start and end tag or be self closing.
(no further stacktrace/information to indicate what the malformed meta tag was)
I can't debug what the malformed meta
tag is so I have no idea where the problem lies. Any suggestions?
Okay, I feel really stupid for not checking this before I posted the question, but apparantly, it was the input that was messing the TagHelper
up.
It says Tag helpers must have a start and end tag or be self closing.
Apparantly, this means that the meta
element that comes in must have a end tag or be self closing, which (as shown in my before/after samples) my meta
elements did not have.
So to fix, I simply had to make the input meta
tags self closing (i.e. add a /
before the closing >
):
<meta name="js" content="script" data-async="true" data-data-main="requirejs/product-overview/init" data-src="/js/libs/require.js"/>`