Basic rendering with RazorEngine

Rendering templates in code is very easy. The following creates template from a string and passes a model to be rendered into this string:

string template = @"Hello World @Model.Name. Time is: @DateTime.Now";

var host = new RazorEngine();
string result = host.RenderTemplate(template,new { Name="Joe Doe" });

The second parameter passed to RenderTemplate() is the model, which becomes visible in the template as a Model property like @Model.Name. In the example above the model is dynamic.

You can optionally pass a strongly typed model:

string template = 
@"@model MyApp.Person
Hello World @Model.Name. Time is: @DateTime.Now";

var host = new RazorEngine();
string result = host.RenderTemplate(template,new Person() { Name="Joe Doe" });

You can also create a template, compile it and then cache it so you can reuse it later:

string template = @"Hello World @Model.Name. Time is: @DateTime.Now";
var host = new RazorEngine<RazorTemplateBase>();
host.AddAssembly("System.Data.dll");  // add any assemblies you need in templates            
    
string compiledId = host.CompileTemplate(template);    
string result = host.RenderTemplateFromAssembly(compiledId,
												new Person() { Name = "Joe Doe" });

// Run again later without recompilation
string result = host.RenderTemplateFromAssembly(compiledId,
												new Person() { Name = "Rick Strahl" });

The latter allows you to capture the compiled id which points to a cached template assembly in the current RazorEngine instance. Running an already compile template is considerably faster and saves resources as no new assembly is created each time you run the same template.

Caching is Important

Razor compiles every template into code and compiles the template into an assembly. Without caching, templates are constantly recreated and new assemblies are created which wastes resources. Since assemblies can't unload this basically means you have a memory leak. Cache your templates either as described above, or use one of the host containers which automatically cache templates/assemblies and detect when they change.

A better way for persisting templates is to use one of the Razor Host Containers provided.


© West Wind Technologies, 2018 • Updated: 05/29/17
Comment or report problem with topic