[TargetElement("div")] [TargetElement("style")] [TargetElement("p")] public class ConditionTagHelper : TagHelper { public bool? Condition { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { // 如果设置了condition,并且该值为false,则不渲染该元素 if (Condition.HasValue && !Condition.Value) { output.SuppressOutput(); } } }
4. 自定义元素的TagHelper
如果我们要为自定义元素定义TagHelper,则我们要符合约定规范,示例代码如下:
public class WebsiteInformationTagHelper : TagHelper { public WebsiteContext Info { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "section"; output.PostContent.SetContent(string.Format( "<p><strong>Version:</strong> {0}</p>" + Environment.NewLine + "<p><strong>Copyright Year:</strong> {1}</p>" + Environment.NewLine + "<p><strong>Approved:</strong> {2}</p>" + Environment.NewLine + "<p><strong>Number of tags to show:</strong> {3}</p>" + Environment.NewLine, Info.Version.ToString(), Info.CopyrightYear.ToString(), Info.Approved.ToString(), Info.TagsToShow.ToString())); output.SelfClosing = false; } }
则使用的时候,我们需要使用website-information标签,并将info属性赋值一个强类型的值,示例如下:
<website-information info="new WebsiteContext { Version = new Version(1, 1), CopyrightYear = 1990, Approved = true, TagsToShow = 30 }"/>
其渲染结果,则是渲染成一个包含4个p元素的section元素。