Background:
We are writing a new task for the ArcGis Explorer, this task needs to place images on the globe using its X,Y coordinates.
While for each instance on the globe we need to render its details as html.
Mission:
Rendering the objects to html, we are still didn't find the right place (on the server or on the client), but let assume that they both need to do the same job.
Ideas:
- Render in code:
This is the naive way of thinking. while you are first thinking about this problem you might think to add the object an ToHtml() method.
Always think about the: Single Responsibility Principle (SRP).
You can still think about Writing an HtmlWriter or HtmlRenderer class that gets object and render the object using reflection or something else, but than you will find yourself indenting you JavaScript\html\CSS in C#, for example you can watch this code:
1: var items = new List<string> {"Shani", "Doron", "Nati", "Yossi"}; 2: var sb = new StringBuilder();
3: items.ForEach(currentItem =>
4: sb.AppendFormat("<li>{0}</li>", currentItem) 5: );
6: string data = sb.ToString();
Let's think about the time we will need to change the UI from <li> to one with style or maybe even change the list to be styled as table...
- XSL - is pretty more dynamic than code, isn't it?
So we are now looking for something more dynamic, something that we can read from a file so we can give it to our designer to play with the UI.
This lead us to the second option: at my past all our reports were rendered using XSL files, personally I don't like this option.
But the main reason is that we will need to serialize our objects to XML, while in most cases all you need is to render only few fields.
- Let's found another Template Engine:
The first one I can think of is the MVC Engine or Brail. after some searching reading and Testing I found StringTemplate.
Here is a simple code for using the API:
1: var templateFolder = new StringTemplateGroup("SimpleLoopTemplate", @"\TemplateEngineTestCase\WinApp"); 2: var template = templateFolder.GetInstanceOf("3_simpleLoop"); 3: //here we are binding our list to the template
4: template.SetAttribute("items", new List<string> {"Shani", "Doron", "Nati", "Yossi"}); 5: var data = template.ToString();
and here is the template (file name:
3_simpleLoop.st):
1: $items: {num1| 2: <li>$num1$</li>
3: }$
4: $end$
Conclusion:
The StringTemplate give us an API to solve our problem - and using such code and template we can render our Models to different Views.
But is this API is easy or even stable?
In later posts we will see more samples using the StringTemplate.
Hopefully samples for using Brail too.