Generating strongly typed content links in ASP .Net MVC with T4 templates – Part 2
In my previous post I took a look at generating the static content links we use in ASP .Net using T4 templates. There were a couple of issues which I pointed out and some others which were pointed out to me.
My code is wrong
In more than one way. Take a look at the generated code:
Yup, I missed it – the generated links are actually wrong. I obviously got too excited that it was actually working (after fighting the T4 monsters for quite a while). It’s an easy fix. The root path should simply change from
to
Rendering links in the head section
The next mistake I made was with the rendering of the link tag for the stylesheet.
The rendered link looks like this:
David Ebbo pointed out what was happening as well as an obvious workaround.
When you use the expression with the double quotes, the parser gets confused because they conflict with the double quotes for the href attribute. So it doesn’t treat the link tag as anything special. But with the improved expression, there are no double quotes. Workaround? Add +””. I know, not pretty, there may be a better one.
The problem is only specific to the head section – if I put the exact same code in the body section the rendered code is correct.
In my previous post I also mentioned that I’m not replacing the entire Url.Content call – I’m simply trying to remove the dependency on strings. However, in this instance I think replacing the entire link tag would be the best option. I simply added 2 extension methods.
This allows us to render stylesheet (and scripts) using the helper methods.
I usually prefer not to use helpers which generate complete html elements since (in my opinion) it makes the code less readable, but in this case the syntax works very nicely.
Sanitize the input
Something that I didn’t mention (which actually works correctly, * gasp *) is the need to sanitize the input. For example, the script named Jquery-1.3.2-Vsdoc.js needs a variable name similar to Jquery132Vsdoc. I did the transformation using a regular expression.
While this will work for the Jquery-1.3.2-Vsdoc.js example, we still need to exclude all C# keywords. For example, an image named ‘lock’ will generate compilation errors since ‘lock’ is a reserved word.
Unfortunately there is no way to access a list of C# keywords programmatically – the best we can do is to maintain a list in code and check against this list.
This will correctly generate variable names for any content.
Using MVC T4 templates
As I mention, the obvious next step is for a single template that can be included in any project. Thanks to David Ebbo the MVC T4 template (now named T4MVC) is now available on CodePlex, as one of the downloads in the ASP.NET MVC v1.0 Source page.