F# + Razor View Engine = FSRazor


Last month InfoQ posted some info from the ASP.NET team about using F# with the new Razor view engine. It seemed like it should be pretty simple, so I thought I’d give it a shot. My (very rough) progress so far is available on GitHub. The solution includes a sample project with a simple F# view using expression blocks:

<h2>@("FS" + "Razor")</h2>
<p>@(
    let even_odd s =
        match s % 2 with
        | 0 -> sprintf "%i is even!" s
        | _ -> sprintf "%i is odd!" s
    DateTime.Now.Second |> even_odd
    )</p>

A useless example, but it works…as long as there aren’t unmatched parentheses (within a string or comment). So far the parser is a simple port of the C# parser, and as such is very procedural—it’s unclear if the underlying parser model will afford much wiggle room to take advantage of F#.

It’s been an interesting learning experience, as my first attempt to do “normal .NET” inheritance-based development in F#. Some random thoughts based on work so far…

  • I still struggle to remember F#’s syntax for familiar class constructs (ctor, method, property, etc)
  • I’ve been disappointed so far by my attempts to F#-ize the C# port
  • I finally bothered to look up how to add assembly information in F#
  • I learned about a few new ASP.NET 4 features, in particular PreApplicationStartMethodAttribute which uses a magic string (read: undiscoverable) to identify a method which can register the .fshtml build provider

There’s still a bunch of work yet to do, and I’d love some help if anyone is actually interested in using this in production…

  • Tests for the parser and code generator
  • Handling implicit transitions (@ without explicit block)
  • Handling strings/comments
  • Handling statement blocks
  • Figuring out where F# needs special treatment in Razor (extra features or syntax that won’t work)
  • MVC support? (@model)
  • WebPages support? (branch doesn’t work yet)
Red Gate should have said…