问题描述
我正在努力了解如何在HtmlTargetElement类属性中显示分配给Attributes的字符串。我有几个问题,我认为这将突出我的问题和理解。
I'm wrestling with understanding how to show the string assigned to Attributes in the HtmlTargetElement class attribute works. I have a couple questions that I think will highlight my issue and understanding.
假设我们只想在make以gm开头且有任何模型时才激活Html元素。我认为有一种方法可以使用单个类属性(而不是多个属性)来做到这一点。
Let's say we want activate an Html Element only when make starts with gm and there is any model. I think there is a way to do this with a single class attribute (not multiple ones).
我正在尝试以下操作,但这只是SWAG,不能正常工作。我将不胜感激技巧,因此我可以理解该文档说该属性可以采用查询选择器(如字符串)的含义。
I'm trying the following but it is just a SWAG and does not work. I'd appreciate tips so I can understand what the doc means when it says that this attribute can take a "query selector like string".
Tag Helper类
The Tag Helper Class
[HtmlTargetElement("auto-price", Attributes = "[make^=gm][model]")]
public class AutoPriceTagHelper : TagHelper
{
和剃刀标记
<auto-price make="gm" model="volt" ></auto-price>
<auto-price make="ford" model="mustang"></auto-price>
<auto-price make="ford" ></auto-price>
<auto-price test></auto-price>
推荐答案
它实际上像您期望的那样工作。您唯一缺少的是 Attributes
是用逗号分隔的属性列表,因此当指定多个时,您需要使用逗号,如 Attributes = [make ^ = gm],[model]
。
It actually works like you were expecting. The only bit your are missing is that Attributes
is a comma-separated list of attributes so when specifying more than one you need the commas as in Attributes = "[make^=gm],[model]"
.
以下是您的帮助程序的模拟版本:
So the following mock version of your helper:
[HtmlTargetElement("auto-price", Attributes = "[make^=gm],[model]")]
public class AutoPriceTagHelper : TagHelper
{
public string Make { get; set; }
public string Model { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "ul";
output.Content.SetHtmlContent(
$@"<li>Make: {Make}</li>
<li>Model: {Model}</li>");
}
}
具有以下剃刀标记:
<auto-price make="gm" model="volt" ></auto-price>
<auto-price make="ford" model="mustang"></auto-price>
<auto-price make="gmfoo" model="the foo"></auto-price>
<auto-price make="gmbar"></auto-price>
<auto-price test></auto-price>
将仅匹配第一个和第三个外观,因为它们是同时具有两个必需属性的唯一外观( make
和 model
),并匹配前缀条件 ^ gm
make
属性。
Will match only the first and third appearances as they are the only ones with both required attributes (make
and model
) and matching the prefix condition ^gm
for the make
attribute.
生成的html如下所示:
The resulting html looks like this:
<ul><li>Make: gm</li>
<li>Model: volt</li></ul>
<auto-price make="ford" model="mustang"></auto-price>
<ul><li>Make: gmfoo</li>
<li>Model: the foo</li></ul>
<auto-price make="gmbar"></auto-price>
<auto-price test=""></auto-price>
这篇关于如何在HtmlTargetElement(标签助手)中使用Attributes属性来定位一个或另一个标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!