Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
ASP.NET MVC and NHaml

I started playing with NHaml lately for sheer curiosity. It comes with MVCContrib and that's what I've been using to explore it.

I'm not completely on board yet that you'll want to write all your views, for all kinds of application scenarios using NHaml. I know someone will probably jump out and say that their entire site was built with NHaml and it's wonderful. I'm sure it can be done, I'm just still wondering if it's more trouble than necessary. On the other hand, if you are starting a new application from scratch (i.e. you are not inheriting any existing template or that sort of thing,) then NHaml can guide you through a different way of thinking about your views and simplify them a lot.

I might have already said this before, but I'm generally in favor of working as close to the platform as possible and viable. That's why I'm not a big fan of things like Script#, RJS, and Volta. NHaml is almost in the same category but it does bring some nice things to the table and that's why I'm not ready to dismiss it just yet. Just take a look at what our HTML looked like circa 1998 and what it is now with richer CSS and JavaScript.

As much as I can, I try to separate my (X)HTML from my CSS and my JavaScript. Sometimes it gets to the point that I wonder why I am using HTML to begin with — it's all data and structure. I wonder how long until we have a WikiText or MarkDown view engines.

NHaml fits well for these kinds of well-separated HTML views. It does away (kind of) with the HTML tags and focus on the structure and meaning of each piece of information. Because it defines structure in a way that works well with CSS, it also works great with jQuery for our JavaScripts. It's unobtrusive JavaScript heaven!

I think the key to learning NHaml is forgetting about HTML and its tags (or at least don't focus on them). Forget that the page ultimately rendered will be in HTML. For a moment just visualize the areas of the page as meaningful pieces of data: sidebar, lists, headings, article title, article body, author name, navigation tabs, etc, not divs, tables, spans, fieldsets, etc.

Less Noise More Content

The most obvious impression you get when looking at a NHaml template for the first time is how skinny it is compared to any tag-based template. Your eyes are used to look for angle brackets to help you understand the structure of the document, but in NHaml the indentation serves that purpose.

Take a look at a common template to create a grid of products in ASPX.

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<head>
		<title><%= ViewData["pagetitle"] %></title>
	</head>
	<body>
		<h1>All Products</h1>
		<table class="grid" id="products">
			<tr>
				<th>ID</th>
				<th>Name</th>
			</tr>
			<% foreach(var prod in (IEnumerable<Product>)ViewData["products"])  { %>
				<tr>
					<td><%= prod.ID %></td>
					<td><%=  prod.Name %></td>
				</tr>
			<% }  %>
		</table>
		<input type="button" value="Say Hi" onclick="alert('Hi');" />
	</body>
</html>

Now take compare that to the NHaml version.

!!! XML
!!!
%html
  %head
    %title= ViewData["pagetitle"] 
    %body
      %h1 All Products
        %table.grid#products
          %tr
            %th ID
            %th Name
          - foreach(var prod in (IEnumerable<Product>)ViewData["products"])
          %tr
            %td= prod.ID
            %td= prod.Name
        %input{ type="button", value="Say Hi", onclick="alert('Hi');"}/

Never Forget a Closing Tag Again

Having meaningful indentation brings the common advantage of needing to explicitly mark the end of a block, making that automatic. In other words, the closing tags are added at the right places for you. That's something I value a lot.

Identifiers and Selectors, Css-Friendly

By now, after looking at the above NHaml sample a few times, you probably noticed that the class and id attributes are set using a dot and a # sign, respectively.

%table.grid#products

Not by coincidence, that's the same type of syntax you'll find in CSS selector rules. Another plus for NHaml here, one less syntax to be memorized — or eventually mismatched.

Server Side Code/Tokens Syntax

Server side statements are simply prefixed with a dash and a space. The code blocks are also delimited using indentation (notice the lack of curlies in the foreach loop.)

 - foreach(var prod in (IEnumerable<Product>)ViewData["products"])
 %tr
   %td= prod.ID
   %td= prod.Name

I'm a little bit uneasy with this code formatting but, to be fair with NHaml, I haven't played with that aspect of it enough yet.

Let's Throw jQuery in This Mixture

Oh, about those CSS selectors I mentioned above. That goes very well with jQuery as well since jQuery uses CSS selection rules as well. That's one more reason NHaml can help you keep the HTML/CSS/JavaScript triad separated.

More to come (hopefully)

I plan to explore it a little more, especially with MVC in mind, and I'll try to get to some conclusion in a later post.


Posted 10-29-2008 5:02 PM by sergiopereira
Filed under: ,

[Advertisement]

Comments

ASP.NET MVC Archived Blog Posts, Page 1 wrote ASP.NET MVC Archived Blog Posts, Page 1
on 10-30-2008 12:33 AM

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

Reflective Perspective - Chris Alcock » The Morning Brew #212 wrote Reflective Perspective - Chris Alcock &raquo; The Morning Brew #212
on 10-30-2008 4:31 AM

Pingback from  Reflective Perspective - Chris Alcock  &raquo; The Morning Brew #212

Stuart Thompson wrote re: ASP.NET MVC and NHaml
on 10-30-2008 10:50 AM

Very cool.  Thanks for the overview.

Sergio Pereira wrote ViewEngines at Chicago ALT.NET
on 10-30-2008 11:18 PM

One of the reasons I&#39;ve been mucking with NHaml is the upcoming meeting of the Chicago ALT.NET group

I am a team member of the NHaml project - Lanwin dev home wrote I am a team member of the NHaml project - Lanwin dev home
on 12-05-2008 4:46 PM

Pingback from  I am a team member of the NHaml project -  Lanwin dev home

Saurabh wrote re: ASP.NET MVC and NHaml
on 02-04-2009 7:49 AM

Hi.....

m using Asp.Net MVC RC1

in that m using NHaml

by using NHaml m getting this error:

<%@ Application Codebehind="Global.asax.cs" Inherits="NHaml.Samples.Mvc.Global" Language="C#" %>

any Ideas?

Kind Regards,

Saurabh

sergiopereira wrote re: ASP.NET MVC and NHaml
on 02-04-2009 8:29 AM

@Saurabh, I'd imagine that's not the error you're getting, probably jut part of the error message. Could you post the entire error message if that's the case.

Normally errors that print out directives ( <%@  %> ) from the .asax or .aspx files are related to compilation problems. Check if your Global class in Global.asax.cs is still inside the namespace NHaml.Samples.Mvc.

Saurabh wrote re: ASP.NET MVC and NHaml
on 02-04-2009 8:50 AM

m sorry.......the error is this:

Could not load type 'NHaml.Samples.Mvc.Global'.

i have checked my Global.asax it is inside the NHaml.Samples.Mvc

Kind Regards

Saurabh

sergiopereira wrote re: ASP.NET MVC and NHaml
on 02-04-2009 8:59 AM

@Saurabh, this error can be caused by compilation or missing references. Check if your project compiles and that all the necessary dlls are being put in the bin directory (or the GAC if you use that.)

Saurabh wrote re: ASP.NET MVC and NHaml
on 02-04-2009 9:07 AM

i download the sample code from

code.google.com/.../list

it is a zip file i extract it and use the sample project which is placed on "[Directory]\Samples\MVC"

I have checked alll the refernce ......all are fine.......

m not sure but i think.....this error is coming cause of Asp.Net MVC Release Candidate....

tell me if m wrong.

Kind Regards,

Saurabh

Carlo Bertini wrote re: ASP.NET MVC and NHaml
on 02-22-2009 1:39 PM

@Saurabh

Asp.net MVC RC1 work olgy with source , not with "compile" version.... check this post to create a new application

blog.brianhartsock.com/.../nhaml

ps: sorry , my english is very poor

WaYdotNET

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)