开发者

How to create nested <ul> <li> tags with HtmlTags (FubuMVC)

开发者 https://www.devze.com 2023-04-11 15:08 出处:网络
I have no previous experience with FubuMVC HtmlTags library, and I simply got stuck when trying to accomplish a simple nested structure like this:

I have no previous experience with FubuMVC HtmlTags library, and I simply got stuck when trying to accomplish a simple nested structure like this:

<ul>
 <li>text</li>
 <li>text
   <ul>
     <li>subtext</li>
     <li>subtext</li>
   </ul>
 </li>
 <li>text</li>
</ul>

Here's how I have it when building the string:

public static HtmlString ChildNodesRecursive(DocumentNode documentNode)        
{
    var tag="";
    if (documentNode.Children.Count > 0)
    {
        tag = "<ul>";
        foreach (var c in documentNode.Children)
        {
            tag += "<li>" + c.Name;
            tag += ChildNodesRecursive(c);
            tag += "</li>";
        }
        tag += "</ul>";
    }
    return new HtmlString(tag);
}

Works fine, but I like to use HtmlTags library (outside of FubuMvc, with the HtmlTags separate Nuget).

Edit : I got inspiration from both answers and came up with what I needed. So here's the 开发者_开发技巧code I ended up using.

    public static HtmlTags.HtmlTag ChildNodesRecursiveHtmlTag(DocumentNode documentNode)
    {
        var ul = new HtmlTags.HtmlTag("ul");
        foreach (var c in documentNode.Children)
        {
            var li = new HtmlTags.HtmlTag("li");
            li.Add("a").Attr("href",c.ContextFullPath).Text(c.Name);
            if (c.Children.Count > 0)
            {
                li.Children.Add(ChildNodesRecursiveHtmlTag(c));
            }
            ul.Children.Add(li);
        }
        return ul;
    }


I can give you an example which may make things clearer to you:

var ul = new HtmlTag("span").AddClass("form_input");
ul.Modify(t =>
{
           foreach (var value in choice)
           {
               t.Add("input")
                   .Attr("type", "radio")
                   .Attr("name", request.Accessor.Name)
                   .Attr("value", value)
                 .Add("span")
                   .AddClass("fixed-width")
                   .Text(value);
           }
});

Gives you something like

<span class="form-input">
  <input type="radio" name="bla" value="foo" />
  <span class="fixed-width">foo</span>
  ...etc...
</span>

You can carry on nesting tags with modify and filling in the lambda. I think you will find that what you want to do is possible with the bits of syntax shown.


This code:

var root = new HtmlTags.HtmlTag("ul");
root.Add("li").Text("item1");
var child = root.Add("ul");
child.Add("li").Text("item2");
return root.ToPrettyString();

produces the following output:

<ul>
  <li>item1</li><ul>
    <li>item2</li>
  </ul>
</ul>
0

精彩评论

暂无评论...
验证码 换一张
取 消