103

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.

Thomas
  • 7,933
  • 4
  • 37
  • 45

6 Answers6

79

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://vibrantcode.com/blog/2010/11/16/hosting-razor-outside-of-aspnet-revised-for-mvc3-rc.html
  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 treated 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!
}
Charles Lambert
  • 5,042
  • 26
  • 47
marcind
  • 52,944
  • 13
  • 125
  • 111
  • 2
    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 Sep 03 '10 at 07:23
  • 6
    @Thomas Razor should do just fine in those scenarios, you're just going to have to add those magic `` 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 Sep 03 '10 at 15:42
32

Check RazorEngine, it's a little framework built on top of Razor that allows you to do this.

TrueWill
  • 25,132
  • 10
  • 101
  • 150
Ariel
  • 1,641
  • 1
  • 18
  • 27
20

Take a look at RazorTemplates library. It's more lightweight than RazorEngine library, it's thread-safe and has very nice minimal interface.

Compiling and rendering a template is as simple as two lines of code:

var template = Template.Compile("Hello @Model.Name!");
Console.WriteLine(template.Render(new { Name = "World" }));
alexey
  • 8,360
  • 14
  • 70
  • 102
8

Both RazorEngine and RazorTemplates are already mentioned here, but check out RazorMachine. You can simply point your non-MVC app to a ~/Views folder of (another) existing MVC app, execute with sending proper model and get rendered output on 2 lines of code:

var sb = new StringBuilder();

//RazorMachine magic:
//*tweets* is basically List<TwitterPost> - simple collection of custom POCO
//first param for rm.ExecuteUrl points to ~/Views folder, MVC style
var rm = new RazorMachine(htmlEncode: false);
ITemplate template = rm.ExecuteUrl("~/twitter/twitter", tweets);

//do whatever you want with result
sb.Append(template);
Antonin Jelinek
  • 2,277
  • 2
  • 20
  • 25
3

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

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • This needs upvotes because T4 has similarities to Razor and is an actual all-purpose code generator that ships out of the box as a feature in Visual Studio - essentially it's an all-purpose 'Razor' – Dan Ling Jul 01 '15 at 22:02
  • It is my understanding that T4 templates can only be changed at compile time, the .tt file is converted to and saved as a .cs file. In my usage a semi- technical user would like to update the template without having to rebuild the application. Is there an easy way that this can be achieved using T4 templates? – daveb Mar 22 '17 at 16:06
  • Well possibly, as long as whatever it is generating can be interpreted, like CSHTML can be by the Razor engine at runtime. You can also programmably trigger it to generate code, but compiled code has to be parsed by the compiler to be useable.... – Brian Mains Mar 27 '17 at 19:39
2

Its May 2022 and I kissed a few frogs before finding this blog: https://soundaranbu.medium.com/render-razor-view-cshtml-to-string-in-net-core-7d125f32c79

VERY easy to use along with a .Net Core Razor Class Library (RCL) and this small library: RazorTemplating

using Razor.Templating.Core;

var model = new ExampleModel()
{
    PlainText = "This text is rendered from Razor Views using Razor.Templating.Core",
    HtmlContent = "<em>You can use it to generate email content, report generation and so on</em>"
};

// Both ViewBag and ViewData should be added to the same dictionary. 
var viewDataOrViewBag = new Dictionary<string, object>();
// ViewData is same as mvc
viewDataOrViewBag["Value1"] = "1";

// ViewBag.Value2 can be written as below. There's no change on how it's accessed in .cshtml file
viewDataOrViewBag["Value2"] = "2";

var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewDataOrViewBag);
jenson-button-event
  • 18,101
  • 11
  • 89
  • 155