Is there any way to create looping with Tag Helpers?

前端 未结 1 1054
轻奢々
轻奢々 2021-02-15 14:09

Is there any way to create a Tag Helper that somehow iterates (repeater like) over the inner tag helpers? That is, something like:



        
1条回答
  •  暖寄归人
    2021-02-15 14:52

    It's possible, by using the TagHelperContext.Items property. From the doc:

    Gets the collection of items used to communicate with other ITagHelpers. This System.Collections.Generic.IDictionary is copy-on-write in order to ensure items added to this collection are visible only to other ITagHelpers targeting child elements.

    What this means is that you can pass objects from the parent tag helper to its children.

    For example, let's assume you want to iterate over a list of Employee :

    public class Employee
    {
        public string Name { get; set; }
        public string LastName { get; set; }
    }
    

    In your view, you'll use (for example):

    @{ 
        var mylist = new[]
        {
            new Employee { Name = "Alexander", LastName = "Grams" },
            new Employee { Name = "Sarah", LastName = "Connor" }
        };
    }
    
        
    
    

    and the two tag helpers:

    [HtmlTargetElement("big-ul", Attributes = IterateOverAttr)]
    public class BigULTagHelper : TagHelper
    {
        private const string IterateOverAttr = "iterateover";
    
        [HtmlAttributeName(IterateOverAttr)]
        public IEnumerable IterateOver { get; set; }
    
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "ul";
            output.TagMode = TagMode.StartTagAndEndTag;
    
            foreach(var item in IterateOver)
            {
                // this is the key line: we pass the list item to the child tag helper
                context.Items["item"] = item;
                output.Content.AppendHtml(await output.GetChildContentAsync(false));
            }
        }
    }
    
    [HtmlTargetElement("little-li")]
    public class LittleLiTagHelper : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            // retrieve the item from the parent tag helper
            var item = context.Items["item"] as Employee;
    
            output.TagName = "li";
            output.TagMode = TagMode.StartTagAndEndTag;
    
            output.Content.AppendHtml($"{item.Name}{item.LastName}");
        }
    }
    
        

    0 讨论(0)
    提交回复
    热议问题