43

I need to merge templates with data to create unique strings at runtime. It was suggested that I look at the Razor templating view engine that comes in ASP.NET MVC 3. Looks great, but I need to use it outside of MVC view creation.

I know I can use the core Razor engine directly, but I've also found a couple of projects that make using Razor directly easier. Like:

  1. Rick Strahl's Razor Hosting Template Engine- http://www.west-wind.com/weblog/posts/864461.aspx
  2. Razor Engine on GitHub - https://github.com/Antaris/RazorEngine

Does anyone have any guidance on using Razor outside of MVC as a standalone template engine? Any experience with these wrapper projects? are there other Razor hosting implementations I should look into?

Makyen
  • 29,855
  • 12
  • 76
  • 115
Michael Levy
  • 12,897
  • 15
  • 62
  • 99

6 Answers6

7

You may take a look at the following blog post which illustrates how you could use the Razor view engine to render a template to a string.

Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902
6

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

alexey
  • 8,228
  • 11
  • 66
  • 100
6

If you want to generate real content from razor template, you can use RazorEngine.

Marcos Dimitrio
  • 6,100
  • 4
  • 35
  • 59
mahesh
  • 288
  • 3
  • 2
4

Phil Haack posted about this way to do it using a generated class.

  • You create a .cshtml file and then use a compile time extension on the file to generate a class. Then you can just do this:

    var template = new RazorTemplate {
        Model = new[] { 
            new {Name = "Scott", Id = 1},
            new {Name = "Steve", Id = 2},
            new {Name = "Phil", Id = 3},
            new {Name = "David", Id = 4}
        }
    };
    Console.WriteLine(template.TransformText());
    
Simon_Weaver
  • 130,769
  • 75
  • 612
  • 659
  • Simple takes the day in my book. Thanks for dropping this @Simon_Weaver! You seem like a guy who might just hang out with @JonSkeet you have so much SO cred! :-) It pays to dig through all the answers. :-) – Norman H Feb 16 '15 at 20:17
3

There is a nice post how to use RazorEngine: How to create a localizable text template engine using RazorEngine

Malkov
  • 680
  • 1
  • 6
  • 8
3

Found a really nice library by Jaap Lamfers:

Razor 2.0 template engine, supporting layouts (on CodeProject)

RazorMachine (on GitHub)

Qualities:

  • support _ViewStart
  • support Layout
  • extensible (supports something like MVC ViewEngines)
  • contains samples
  • lots of unit tests
  • it is well documented (see CodeProject link)
Miguel Angelo
  • 23,308
  • 16
  • 56
  • 81