Art Of Programming

musings by Dmytrii Nagirniak

Simplify Iteration in MVC Views With NHAML

This post is inspired by the one from Steve Sanderson. He wants to improve the table generation on the WebForms engine in ASP.NET MVC. I definitely recommend to switch to NHAML instead.

This is how it would look: (there is no tbody - must be Steve’s mistake, anyway I’ll leave it as is)


%table
  %thead
    %th Rank
    %th Name
    %th Age
  %tbody
    - var people.Model.ToList();
    - for(int index=0; index<people.Count; index++) {
      - var cssClass = "myitem-" + (index % 2 == 0 ? "odd" : "even");
      - if (index == people.Count-1) cssClass += " myitem-last";
        %tr {class=cssClass}
          %td
            = index + 1
            .
          %td
            &= people[index].Name
          %td
            &= people[index].Age



And this is much more readable for me, especially comparing to the original.
Also keep in mind there are no any extension methods used, just pure C# and NHAML.
Adding some extension methods I would probably make it look like this:


%table
  %thead
    %th Rank
    %th Name
    %th Age
  %tbody
    - for(int index=0; index<Model.People.Count; index++) {
        %tr{ class=#{Model.People.RowClassFor(index)} }
          %td
            = index + 1
            .
          %td
            &= people[index].Name
          %td
            &= people[index].Age



And we have only simplest possible extension method: RowClassFor. It can be reused in all the tables so you don’t need to modify million of view in order to change css classes.
Looks much better? Don’t you agree?

Comments

Dmytrii Nagirniak
The NHAML community is not very large but it is under continuous development and improvement. There are couple nice fellas working on it. Check the SVN history and you will see.

Additionally there are large number of tests for NHAML. So I can sleep well using it.

Also you can easily contribute to it and are very welcome to do so. Just ask at the user groups and I believe you will get invited.
Anonymous
Hi - I accidentally discovered NHaml and like what I have seen so far. However, the community seems very quiet and not a lot seems to be happening. Am I missing something or is NHaml winding down.

I would appreciate any information available.

Comments