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

2

1

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;
    }
Loathing answered 9/10, 2011 at 17:42 Comment(2)
And the DocumentNode class is..?Kufic
{string Name, List<DocumentNode> Children}Loathing
L
3

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.

Listlessness answered 9/10, 2011 at 18:4 Comment(0)
K
1

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>
Kufic answered 9/10, 2011 at 18:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.