fubumvc

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


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;
    }

Solution

  • 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.