views:

153

answers:

3

If I look at the Razor View Engine, then I see a very nice and concise syntax that is not particularly tied to generating html. So I wonder, how easy would it be to use the engine outside asp.net in a "normal" .net environment for example to generate text, code,...

Any pointer, example, comment or explanation is welcome.

A: 

Generate code or text: you mean like T4 Templates: http://msdn.microsoft.com/en-us/library/bb126445.aspx or codesmith tools?

Brian
A: 

Andrew Nurse, who works on the Razor View Engine has a nice blog post about using the Razor View Engine outside of asp.net. http://blog.andrewnurse.net/2010/07/22/UsingTheRazorParserOutsideOfASPNet.aspx

BuildStarted
+8  A: 

There are two issues here:

  1. Yes, you can run the Razor View Engine outside of the context of an ASP.NET app domain, as explained in Andrew's blog: http://blog.andrewnurse.net/2010/07/22/UsingTheRazorParserOutsideOfASPNet.aspx
  2. However, Razor is still primarily focused on generating xml-like markup (e.g. HTML) in the sense that the Razor parser uses the presence of <tags> to determine the transition between code and markup. You can probably use it to generate any text but you might run into issues when your output doesn't match Razor's assumptions about what your intentions are.

So for example while this is valid Razor code (because of the <div> tag):

@if(printHello) {
   <div>Hello!</div>
}

The following snippet is invalid (because the Hello! is still being trated as code):

@if(printHello) {
   Hello!
}

However there's a special <text> tag that can be used to force a transition for multi-line blocks (the <text> tag will not be rendered):

@if(printHello) {
   <text>Hello!
   Another line</text>
}

There is also a shorter syntax to force a single line to transition using @::

@if(printHello) {
   @:Hello!
}
marcind
Well I was thinking about using it to generate things like e-mails or on-the-fly IronPython code generation. Since these don't use tags, it's probably better to look at other alternatives. Thanks for the answer.
Thomas
@Thomas Razor should do just fine in those scenarios, you're just going to have to add those magic `<text>` tags or use `@:` every now and then. Once the VS editor support comes out for the Razor syntax it will be quite easy to tell when the transitions occur.
marcind