I have successfully created the mvc / razor web application that returns css files that have been parsed by a razor. Every time I have a background image, I have a razor fragment that writes the URL prefix to the image file name. CSS now looks like this:
body { background-image: url(@LookupUrl.Image("background.gif")); }
Css files now work fine, and I switched to trying to get javascript.js files to work the same, but they donโt play the ball.
The code is identical to the css code and it successfully finds the .js file, but the razor seems to parse it differently. Here is an example js file:
function testFunction() { alert('test function hit!'); } testFunction();
It seems that Razor thinks this is the code that he should compile and gives an error:
Compiler Error Message: JS1135: Variable 'alert' has not been declared > Source Error: > > Line 1: function testFunction() { > Line 2: alert('test function > hit!'); Line 3: } Line 4: > testFunction();
After renaming the same file to .css it works fine.
Is there a way to get a razor to work with .js files in the same way as for .css?
Here's how I registered the razor file handlers:
RazorCodeLanguage.Languages.Add("js", new CSharpRazorCodeLanguage()); RazorCodeLanguage.Languages.Add("css", new CSharpRazorCodeLanguage()); WebPageHttpHandler.RegisterExtension(".js"); WebPageHttpHandler.RegisterExtension(".css");
The build provider is registered with PreApplicationStart using the Haacked outlines method in its blog post .
Do I need to remove the handler that adds mvc for .js files?
UPDATE 2 days on
While I was working on what I wanted to work on, I would not recommend this method to others. Using Razor to parse css / javascript is erroneous without using <text> <text /> - this is the razor simplicity using @ampersand, which messed it up. Consider the CSS3 @ font-face font. Razor gets to @ and thinks he should use it as a function. The same thing can happen with javascript, and it happened with jQuery 1.5.1.
Instead, I will probably go back to aspx webforms for dynamic css / javascript where there is less chance of <%%> code blocks appearing.