Building Custom Base Templates

When the Razor parser is processing the content of your Razor view, it's actually generating the code of a method (Execute) as a series of Write statements. In the exact same way, this templating engine is creating a class at runtime that inherits from a type that supports Execute and Write operations. The default implementation, TemplateBase (or TemplateBase<T> when using a model) is what we use to create simple templates, e.g:

string template = "This is my sample template, Hello @Model.Name!";
string result = Razor.Parse(template, new { Name = "World"  });

Will result in something similar to:

public class asdascasca : RazorEngine.Templating.TemplateBase<dynamic>
{
  ...
  public void Execute()
  {
    this.Clear();
    WriteLiteral("This is my sample template, Hello ");
    Write(Model.Name);
    WriteLiteral("!");
  }
}

A question I get often asked is where is my @Html support? Much like @Model, @Html is a property of the base WebViewPage in MVC. Out of the box, Razor doesn't actually support it. If I wanted to introduce support for custom properties or methods, I would need to create a custom base template. Here's an example:

public abstract class MyCustomTemplateBase<T> : TemplateBase<T>
{
  public string ToUpperCase(string name)
  {
    return name.ToUpperCase();
  }
}

To use this custom template base, I need to tell the TemplateService hosted by the Razor static class to use it:

Razor.SetTemplateBase(typeof(MyCustomTemplateBase<>));

And then we can fire some code at it:

string template = "My name in UPPER CASE is: @ToUpperCase(Model.Name)";
string result = Razor.Parse(template, new { Name = "Matt" });

We are looking at ways of improving support for base templates in the future.

Last edited Jan 19, 2011 at 10:15 PM by AntarisZX, version 4

Comments

soerin May 22, 2014 at 9:56 AM 
To set the custom templatebase in version 3.3.0:

TemplateServiceConfiguration templateConfig = new TemplateServiceConfiguration
{
Resolver = new TemplateResolver(),
BaseTemplateType = typeof(MyCustomTemplateBase<>)
};
Razor.SetTemplateService(new TemplateService(templateConfig));

Mriswith Jul 2, 2013 at 12:07 PM 
this documentation is out of date.

xps Apr 30, 2013 at 2:23 AM 
The Razor.SetTemplateBase() method no longer seem to exist?

smnbss Jul 20, 2011 at 4:33 PM 
I'm having a problem with Razor.SetTemplateBase(typeof(MyCustomTemplateBase<>));

if the template has the following attribute [RequireNamespaces("System.Web.Mvc", "System.Web.Mvc.Html")] but System.Web.Mvc.dll and System.Web.Mvc.Html,dll assembly are never used anywhere else on the hosting process, those dlls are never loaded and the Compilation fail with the following error:

{c:\Users\{user}\AppData\Local\Temp\jfha1304.0.cs(15,22) : error CS0234: The type or namespace name 'Mvc' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)}