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); } } } }
k3b
source share