Search code examples
c#htmlrenderingtemplate-engine

Rendering C# Objects to Html


We have bunch of Domain Entities which should be rendered to an html format, which shows their detail in a pop up window.

I would be glad to do something like this:

Product product = new Product(...);
product.ToHtml();  // or: HtmlRenderer.Render(Product);

but my main problem is how to do this stuff from behind. I have 3 different answers:

1. Render By Code:

I can simply write my code for rendering the Html inside the ToHtml Method (C#) - the problem it is that it is too static. if you would like to move a little bit the header to the middle you should change code. moreover, it is very hard to read Html indentation in C#.

2. Using XSL:

XSL Files can easily manage the Html template and using XSLT I can transform XML file to the right place of the documents. the parser already written by someone else (just need to learn the syntax) ** for this we will need that each object could serialize to Xml. and if the object changed -> the Xml will be changed --> the xslt need to be changed too ** this will also give me the option to indent the html easily for example: adding css capabilities and\or change the html design

3. using other template engine:

Write my own C# -> Html template Engine so it will read the template from file (*.template) and will insert the right property in the right place of the template using reflection. ** For this solution we have many issues that we can think of, for example: How the syntax should be? Is this thing ok? %Name%

%Description%
And how we can handle arrays? ** Maybe we can use an existing engine (Brail or T4-Templating)?

What do you prefer? Do you know a good engine? For now I prefer the second solution, but it gonna be very slow.


Solution

  • I can't agree more with John Feminella. Integrating Html rendering directly into your domain entities is a horrid pollution of your domain with a completely arbitrary and external concern. Like John said, you will make your entities very brittle by doing that, and break both of those critical rules: Separation of Concerns and Single Responsibility.

    From the choices you gave, #3 is the closest to an appropriate way to do it. You need not write your own template engine. There are plenty free and ready-made template engines on the net that will do the job more than adequately (NVelocity, StringTemplate, Brail, etc. etc.)

    Keep rendering where it belongs...in your presentation/view, and don't pollute your domain with higher level concerns.