Razor syntax - how to conditionally wrap some inner HTML

前端 未结 4 1945
滥情空心
滥情空心 2021-02-02 12:42

In Razor, there\'s a curious rule about only allowing closed HTML within an if block.

See:

Razor doesn't understand unclosed ht

4条回答
  •  耶瑟儿~
    2021-02-02 12:54

    This is IMO the most convenient way to achieve this:

    [HtmlTargetElement(Attributes = RenderAttributeName)]
    public class RenderTagHelper : TagHelper
    {
        private const string RenderAttributeName = "render";
        private const string IncludeContentAttributeName = "include-content";
    
        [HtmlAttributeName(RenderAttributeName)]
        public bool Render { get; set; }
    
        [HtmlAttributeName(IncludeContentAttributeName)]
        public bool IncludeContent { get; set; }
    
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (!Render)
            {
                if (IncludeContent)
                    output.SuppressOutput();
                else
                    output.TagName = null;
            }
    
            output.Attributes.RemoveAll(RenderAttributeName);
            output.Attributes.RemoveAll(IncludeContentAttributeName);
        }
    } 
    

    Then, you just use it like this:

    ...

提交回复
热议问题