Before I invest a lot of time researching Razor and its applicability, I would like to ask you Razor gurus if one could use Razor to generate C# code? Any issues that you can think of right away?
Razor syntax is a simple programming syntax for embedding server-based code in a web page. In a web page that uses the Razor syntax, there are two kinds of content: client content and server code.
It serves as to comment specific part of code or markup which is skipped in output. So if you do @* Some Tags or Code *@ It will just be a comment at server-side.
Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML.
My first try with razor.dll version 2.1.4039.23635 was much easier than i expected
Here is a small working demo
The 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 template looks like this
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>}
}
}
}
Note the <text>
element that prevents razor from interpreting the Debug.WriteLine
The output is
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 would implement @"..."@
or @'...'@
as alias for <text>...</text>
. I added this razorengine.codeplex-Issue as a request to improve. If you plan to use razor as codegenerator please upvote it at razorengine.codeplex-Issue
Edit: as @Epitka suggested, we can use @:
in place 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);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With