Using Custom Template Types
The RazorEngine allows you to create custom templates subclassed from the RazorTemplateBase base class. Custom templates let you add methods and properties to the base template that can facilitate real world templating processing customized to your needs. This is especially useful if you allow end users to customize templates in which case you can create a full object hierarchy ontop of a template class.
There are two ways to use a custom template.
On the RazorEngine
You can specify the template type on the RazorEngine instance, so to create a custom template looks like this:
var engine = new RazorEngine<MyCustomTemplate>();
Now all RenderTemplate() calls automatically use MyCustomTemplate as its base class for the template.
On the Template
You can also explicitly override the template in the template itself by providing an @inherits or @model tag on the first line of the template:
@inherits MyCustomTemplate
or if you want to provide a model (assuming you implemented a generic template that accepts a model type):
@inherits RazorTemplateBase<MyApp.Person>
Using this approach ignores whatever template type was passed to RazorEngine
You can also specifically overrid the Model property on a generic template by using the @model directive:
@model MyApp.Person
The most basic way to render a template with the Razor engine is to use one of the RazorEngine<T>.RenderTemplate()
methods. A variety of overloads exist to render from string and stream inputs to string or stream outputs.
Here's a simple example to render from string input to a string output:
var engine = new RazorEngine();
RazorEngine.AddAssembly("System.Windows.Forms.dll");
// we can pass any object as context - here create a custom context
var model = new CustomContext()
{
WinForm = this,
FirstName = "Rick",
Entered = DateTime.Now.AddDays(-10)
};
string output = engine.RenderTemplate(this.txtSource.Text, model);
if (output == null)
this.txtResult.Text = "*** ERROR:\r\n" + engine.ErrorMessage;
else
this.txtResult.Text = output;
To render to string from a template stored in a file you can use the following overload:
using (reader = new StreamReader("templates\\simple.csHtml", true))
{
result = host.RenderTemplate(reader, new string[] { "System.Windows.Forms.dll" },this.CustomContext);
}
Other overloads allow output to a TextWriter which allows you to write output directly to disk.
© West Wind Technologies, 2018 • Updated: 05/29/17
Comment or report problem with topic