Version 13, last updated by Andrew Davey at September 24, 2009 07:19 UTC
Hasic is a kick-ass view engine for ASP.NET MVC, with a completely different approach. It uses VB.NET's XML literals instead of nasty strings like most other view engines.
That's right, VB! If you are already closing your web browser upon reading that then shame on you. I'm not saying your whole app is in VB, just the views.
Using VB means this stuff comes for free:
- Syntax colouring
- Full intellisense in Visual Studio
- Compiled views
- Extensibility using regular CLR classes, functions etc
Setup is simple, in your Global.asax file:
Dim engine = New Hasic.XDocumentViewEngine() ViewEngines.Engines.Add(engine)
Views are simple VB classes:
Public Class Home Inherits Hasic.XHtmlDocument Protected Overrides Function Body() As XElement Return _ <body> <h1>Hello, World</h1> </body> End Function End Class
You can splice in data using the <%= mydata %> syntax.
A notable difference from aspx views, for example, is that we are building valid XML trees, not blindly slamming strings into a stream. This has a couple of great consequences:
- The XML has to well-formed else the view won't compile.
- We can manipulate the XML document before sending it to the user agent.
Manipulation of the XML is made very easy by using VB's XLINQ features. For example, let's find all the css link elements and make the href URLs versioned.
For Each link In doc...<link>.Where(Function(l) l.@type = "text/css") link.@href = link.@href & "?version=" & GetVersion(link.@href) Next
We can go one step further and use expression trees to drastically manipulate markup at runtime.
<h2>Enter a message</h2> <%= Model.Message.AsForm(Function(m) _ <form method="post" action="/home/messages"> <%= m.Sender.Label("Enter your name") %> <%= m.Text.TextArea().Label("Enter your message") %> <button type="submit">Send</button> </form>) %>
That generates an HTML form using the lambda expression as a template. Those <%= m.SomeProperty %> are expanded into labels and input elements. There are extension methods that alter and enhance the output.