Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML generator for .NET?

Having used Seaside the past few years I've found template systems to be a bad code smell. Is there a framework for .net using something similar to the Seaside canvas system for generating html, css and javascript? Or else a way to avoid the duplication I tend to find in templates.

[Edit] NHaml does not come close to what I'm looking for. The point is not having a shorthand for (X)HTML, but having a programming language in which I can refactor and reuse the code.

In Seaside, it might look like this: (the canvas is the builder of html [and javascript])

renderContentOn: canvas
    canvas form
        class: 'eventEditor';
        with:[
            self renderWhoOn: canvas;
                 renderButtonsOn: canvas]

In this method, I call two subroutines

renderWhoOn: canvas
self decorateDivAndLabel: 'Who' on: canvas around: [
    canvas select
        id: tagId;
        selected: model who;
        list: model whoList;
        callback: [:value | model who: value]]

The first one calls a decorator around a select form element:

decorateDivAndLabel: aString on: canvas around: aBlock
canvas div: [
    canvas label
        for: (tagId := canvas nextId);
        with: aString,':'.
    aBlock value]

This allows eliminating almost all duplication.

like image 306
Stephan Eggermont Avatar asked May 19 '09 16:05

Stephan Eggermont


1 Answers

I have similar feelings about template systems (see ASP.MVC: Implementing a non-templated view engine?), and after experimenting a little, I took the following approach:

  • Implemented a fluent HTML generator C# class which does not write directly to a stream, instead it constructs the whole HTML page as an in-memory object hierarchy.
  • Higher-level (reusable) pieces of HTML code (like complex input controls etc.) are implemented as separate classes and are inserted as nodes into this hierarchy, and can expand themselves into plain HTML nodes automatically.
  • MVC Views are then POCO C# classes which construct the HTML hierarchy and write it out into the response stream.

Some of the benefits (from my perspective):

  • You still retain control over HTML
  • Reusability, inheritance, encapsulation...
  • The result is auto-formatted (indents, XHTML etc.)
  • And best of all... no template scripting using a separate DSL.
like image 144
Igor Brejc Avatar answered Sep 24 '22 02:09

Igor Brejc