【发布时间】:2021-11-14 13:20:28
【问题描述】:
考虑以下自定义 TagHelper 的 Process 函数:
public override async void Process(TagHelperContext context, TagHelperOutput output) {
// ...
var htmlContent = (await output.GetChildContentAsync()).GetContent();
output.Content.SetHtmlContent(htmlContent);
}
我可以使用以下内容,它会渲染嵌套的 taghelper:
<custom-button>
<icon name="search" />
</custom-button>
但是我需要更多类似的东西:
<custom-button icon="search"></custom-button>
这意味着我需要以某种方式在自定义按钮 taghelper 中呈现图标 taghelper。以下是我尝试过但失败的方法:
public override async void Process(TagHelperContext context, TagHelperOutput output) {
// ...
// Set the content (first with the icon tag)
output.Content.SetHtmlContent("<icon name=\"search\" />");
// Render the icon
var htmlContent = (await output.GetChildContentAsync()).GetContent();
// Set the final content
output.Content.SetHtmlContent(htmlContent);
}
有什么办法可以做到吗?
编辑!这是完整的 CustomButtonTagHelper 代码:
[HtmlTargetElement("custom-button")]
public class CustomButtonTagHelper : TagHelper
{
private readonly IFileVersionProvider _fileVersionProvider;
[ViewContext]
public ViewContext ViewContext { get; set; }
public CustomButtonTagHelper(IFileVersionProvider fileVersionProvider)
{
_fileVersionProvider = fileVersionProvider;
}
[HtmlAttributeName("icon")]
public string Icon { get; set; }
public override async void Process(TagHelperContext context, TagHelperOutput output) {
// ...
output.TagMode = TagMode.StartTagAndEndTag;
output.TagName = "button";
// Set the content (first with the icon tag)
output.Content.SetHtmlContent($"<icon name=\"{this.Icon}\" />");
// Render the icon
var htmlContent = (await output.GetChildContentAsync()).GetContent();
// Set the final content
output.Content.SetHtmlContent(htmlContent);
}
}
【问题讨论】:
-
您显示为所需结果的不是标签助手中的标签助手。这是标签上的自定义属性,不符合custom attributes 的推荐标准
-
@devlincarnate
icon属性实际上会在 taghelper 被渲染后消失。 -
另外,你已经遗漏了相关的代码段......我们需要看看在
Process()方法内部调用的那些方法中发生了什么,然后你还需要提供示例输入,以便我们知道传递给Process()' 的内容 -
@devlincarnate 我没有将任何东西传递给
Process(),我什至没有调用它。这一切都由剃须刀处理(我猜)。
标签: c# asp.net-core razor tag-helpers