c# - 如何实现 asp-append-version="true" 到背景图像属性?
问题描述
我正在尝试为asp-append-version="true"
我的图像实现 HTMLTagHelper。问题是关于 DOM 分布,我没有将属性分配给<img>
标签,而是分配给<div>
包含具有属性的图像background-url
。
此外,div 是在所有 DOM 加载之前生成的,我不知道是否会有不同的方法。
一个很明显,将 更改div
为img
标签,但我不希望它,因为我的设计必须保持不变。
到目前为止,我的 javascript 是这样的:
cardHTML += '<div asp-append-version="true" class="card littleCard" style="background-image: url(/Content/Img/Especialistas/LittleCard/' + especialista.idEspecialista + '.jpg' + ')' + '" >';
cardHTML += '</div>';
asp-append-version="true"
不适用于div
标签。关于如何找到处理此问题的方法的任何想法?
谢谢
解决方案
您可以创建自定义TagHelper
以定位具有内联样式属性的所有元素。我尝试过的以下示例看起来工作正常,但如果您想要更标准的东西(类似于ImageTagHelper
, ...),您可以尝试查看基类UrlResolutionTagHelper。我不太确定为什么它需要更复杂,基本上你需要在实际处理它之前解析 URL。我尝试了一个简单的IFileVersionProvider
方法,它也适用于相对路径(当然解析的路径应该位于当前服务器的 Web 根目录)。
下面这个简单的例子可以很好地处理HtmlString
( 几乎是常见的情况,一些自定义渲染可能会注入IHtmlContent
不是 of的属性值HtmlString
,对于这种复杂的情况,您可以参考UrlResolutionTagHelper的源代码,甚至复制几乎完全相同的相关代码很好):
//target only elements having an inline style attribute
[HtmlTargetElement(Attributes = "style")]
public class InlineStyleBackgroundElementTagHelper : TagHelper
{
readonly IFileVersionProvider _fileVersionProvider;
const string BACKGROUND_URL_PATTERN = "(background(?:-image)?\\s*:[^;]*url)(\\([^)]+\\))";
public InlineStyleBackgroundElementTagHelper(IFileVersionProvider fileVersionProvider)
{
_fileVersionProvider = fileVersionProvider;
}
//bind the asp-append-version property
[HtmlAttributeName("asp-append-version")]
public bool AppendsVersion { get; set; }
//inject ViewContext from the current request
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (AppendsVersion)
{
if (output.Attributes.TryGetAttribute("style", out var styleAttr))
{
//the value here should be an HtmlString, so this basically
//gets the raw plain string of the style attribute's value
var inlineStyle = styleAttr.Value.ToString();
var basePath = ViewContext.HttpContext.Request.PathBase;
inlineStyle = Regex.Replace(inlineStyle, BACKGROUND_URL_PATTERN, m =>
{
//extract the background url contained in the inline style
var backgroundUrl = m.Groups[2].Value.Trim('(', ')', ' ');
//append the version
var versionedUrl = _fileVersionProvider.AddFileVersionToPath(basePath, backgroundUrl);
//format back the inline style with the versioned url
return $"{m.Groups[1]}({versionedUrl})";
}, RegexOptions.Compiled | RegexOptions.IgnoreCase);
output.Attributes.SetAttribute("style", inlineStyle);
}
}
}
}
用法:就像您如何使用asp-append-version
on 其他内置标签一样。(就像你的例子一样)。
推荐阅读
- javascript - 了解 indexOf 和 lastIndexOf
- docker - 导出使用 docker-compose 创建的容器
- javascript - 在表单保存按钮上首先触发哪个事件
- javascript - 为 Shopify 开发设置 webpack/HMR
- visual-studio-2017 - MDX 计算年份之间的利润差异(以 % 为单位)
- spring - 无法初始化组件 [org.apache.catalina.webresources.JarResourceSet]
- javascript - 显示意外令牌且无堆栈的模拟器错误
- android - 没有找到无头模拟器
- javascript - 在 Javascript 中断言简单条件而不使用 eval
- javascript - Jquery DataTable 列顺序未与固定标题对齐