Using Razor without MVC
Solution 1
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.
Solution 2
If you want to generate real content from razor template, you can use RazorEngine.
Solution 3
Look at RazorTemplates library. It's more lightweight than RazorEngine library, it's thread-safe and has very nice minimal interface.
Solution 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());
Solution 5
There is a nice post how to use RazorEngine: How to create a localizable text template engine using RazorEngine
Related videos on Youtube
Comments
-
Michael Levy over 3 years
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:
- Rick Strahl's Razor Hosting Template Engine- http://www.west-wind.com/weblog/posts/864461.aspx
- 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?
-
Michael Levy over 12 yearsthat link was in the original question.
-
Norman H about 9 yearsSimple 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. :-)
-
K-Dawg about 5 yearsI thought I'd check this out. It's so simple to use! Thanks!