Fluent interface for rendering HTML

前端 未结 4 1371
不思量自难忘°
不思量自难忘° 2020-12-30 09:21

Rendering HTML with the HtmlTextWriter isn\'t incredibly intuitive in my opinion, but if you\'re implementing web controls in web forms it\'s what you have to work with. I t

4条回答
  •  情书的邮戳
    2020-12-30 10:04

    There are two issues that I see:

    • Repeated use of Tag(Tagname, …). Why not offer extension methods for each tag name? Admittedly, this bloats the interface and is quite a lot to write (=> code generation!).
    • The compiler/IDE doesn't assist you. In particular, it doesn't check indentation (it will even destroy it when you indent your automatically).

    Both problems could perhaps be solved by using a Lambda approach:

    writer.Write(body => new Tag[] {
        new Tag(h1 => "Hello, world!"),
        new Tag(p => "Indeed. What a lovely day.", new Attr[] {
            new Attr("style", "color: red")
        })
    });
    

    This is just one basic approach. The API certainly would need a lot more work. In particular, nesting the same tag name won't work because of argument name conflicts. Also, this interface wouldn't work well (or at all) with VB. But then, the same is unfortunately true for other modern .NET APIs, even the PLINQ interface from Microsoft.

    Another approach that I've thought about some time ago actually tries to emulate Markaby, like sambo's code. The main difference is that I'm using using blocks instead of foreach, thus making use of RAII:

    using (var body = writer.body("xml:lang", "en")) {
        using (var h1 = body.h1())
            h1.AddText("Hello, World!");
        using (var p = body.p("style", "color: red"))
            p.AddText("Indeed. What a lovely day.");
    }
    

    This code doesn't have the problems of the other approach. On the other hand, it provides less type safety for the attributes and a less elegant interface (for a given definition of “elegant”).

    I get both codes to compile and even produce some more or less meaningful output (i.e.: HTML!).

提交回复
热议问题