Use a razor to generate code?

Before investing a lot of time in studying Razor and its applicability, I would like to ask you Razor guru if you can use Razor to generate C # code? Any problems you might think about right away?

+7
source share
3 answers

Of course, you can use Razor to generate C # code, but it is not intended for non-XML-like languages. You must have many <text> tags.

+4
source

My first attempt with razor .dll version 2.1.4039.23635 was much simpler than I expected

Here is a small working demo

codegenerator

using System.Diagnostics; using RazorEngine; namespace CodeGen3b { class Program { static void Main(string[] args) { string template = ... see below; try { string generatedCode = Razor.Parse(template, new { UserNamespace = "MyOwnNamespace" }); Debug.WriteLine(generatedCode); } catch (System.Exception ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); } } } } 

the pattern is as follows

 using System; namespace @Model.UserNamespace { class Program { static void Main(string[] args) { @for(int i = 0; i < 3; i++){ <text>Debug.WriteLine("hello @i " + @Model.UserNamespace); </text>} } } } 

Notice the <text> element that prevents the razor from interpreting Debug.WriteLine

output

 using System; namespace MyOwnNamespace { class Program { static void Main(string[] args) { Debug.WriteLine("hello 0 " + MyOwnNamespace); Debug.WriteLine("hello 1 " + MyOwnNamespace); Debug.WriteLine("hello 2 " + MyOwnNamespace); } } } 

It would be nice if Razor implements @"..."@ or @'...'@ as an alias for <text>...</text> . I added this razorengine.codeplex-Issue as a request for improvement. If you plan to use a razor as a code generator, please increase it by razorengine.codeplex-Issue

Edit: as @Epitka suggested, we can use @: instead of a single-line text tag:

 using System; namespace @Model.UserNamespace { class Program { static void Main(string[] args) { @for(int i = 0; i < 3; i++){ @:Debug.WriteLine("hello @i " + @Model.UserNamespace); } } } } 
+11
source

You can use a razor, like T4 templates, to create any type of text. See This Blog Post.

http://weblogs.asp.net/mikaelsoderstrom/archive/2010/08/03/use-razor-for-t4-templates.aspx

+2
source

All Articles