How to create nested
  • tags with HtmlTags

2019-06-04 09:49发布

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

标签: fubumvc
2条回答
啃猪蹄的小仙女
2楼-- · 2019-06-04 10:19

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>
查看更多
疯言疯语
3楼-- · 2019-06-04 10:39

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.

查看更多
登录 后发表回答