This project is read-only.

Re-compiling of existing templates

Feb 3, 2011 at 5:23 PM
Edited Feb 3, 2011 at 6:09 PM


Firstly, thanks for the great project!

We decided to use it in our last project as a template engine but faced a problem.
In a few words: there are a set of email templates which may be changed, we compile each of them by using of Razor.Compile method. But if template was changed we need to re-compile it. I tried to use this method with the same template name and another template body but unsuccessfully: 

string template1 = "this is a new template, @Model.Name";
string template2 = "this is a very new template, @Model.Name";

Razor.Compile(template1, "test");
Razor.Compile(template2, "test");

string result = Razor.Run(new { Name = "John Dow" }, "test" ); // this will return "this is a new template, John Dow"

The thing is, I can use another template name for the changed template but I also don't want to leave the previous one in the cache. So I'm looking for a possibility to remove/replace compiled template.
Is it possible in the current (2.1) release? 

Thanks in advance!

Feb 3, 2011 at 6:29 PM


You've actually uncovered a bug in the Compile function. Internally it is using the GetTemplate method which actually calls the compiler to create the template, unfortunately the GetTemplate method also checks the cache first and returns the existing compiled template. I'll have a look to fixing this in the next release (v2.2).  In the meanwhile, if you wanted this functionality now, you could download the source, and make the following change:

public void Compile(string template, Type modelType, string name)
    if (string.IsNullOrEmpty(name))
        throw new ArgumentNullException("Pre-compiled templates must have a name", "name");

    var instance = CreateTemplate(template, modelType);

    if (templateCache.ContainsKey(name))
        templateCache[name] = instance;
        templateCache.Add(name, instance);
in \Core\RazorEngine\Templating\TemplateService.cs


Feb 3, 2011 at 6:58 PM

Awesome, thanks!

Mar 15, 2011 at 9:05 PM

Bump :)

Mar 15, 2011 at 10:53 PM

2.2 isn't out - why the bump? :)

Mar 15, 2011 at 11:03 PM

I should have said Bump for wanting this feature in V2.2 and wanting to have V2.2 released.  :)

Oct 6, 2011 at 1:24 PM

I love this project - thank you!  Wonderly elegant API.

This bug is a big deal for us as we effectively can't use Compile (templates change - that's the point).  Any plans for a V2.2 release?

Anything I can do to help get it out the door?

Oct 12, 2011 at 5:47 PM


I'm looking to push v3 onto GitHub real soon (pending free time outside work). There will be a blog post when this happens, and hopefully in the next few weeks.