Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

know if a particular template in RazorEngine is already compiled or not

Tags:

c#

razor

razor-2

Is it possible to know if a particular template is already compiled using the RazorEngine? Basically, if you call:

Razor.Parse("Hello there @Model.Name", model, "hello-world");

This would compile the template using the key 'hello-world'. This might take a couple of milleseconds for the first time, but almost instant for the second time round due to caching. Is it possible to know if a template is already compiled? Something like:

var isCompiled = Razor.IsCompiled("Hello there @Model.Name", "hello-world");
like image 901
Karl Cassar Avatar asked Jun 20 '13 18:06

Karl Cassar


3 Answers

v3.2.0 of RazorEngine includes a ITemplateService.HasTemplate method used to check the cache, but this method doesn't exist on the Razor static type, so to use it you would need to manually instantiate and maintain a TemplateService instance.

Do you actually need to know if they are already cached? I ask because we consider the cache before we start parsing the template, whenever you call ITemplateService.Parse (Razor.Parse).

like image 65
Matthew Abbott Avatar answered Oct 02 '22 09:10

Matthew Abbott


as of 3.4.1.0 Razor.Resolve(templateName) will return null if the template is not in the cache. Which might not be helpful if you are trying to determine if the cache contains the specific version of the text that you sent in.

like image 22
MisterHux Avatar answered Oct 02 '22 09:10

MisterHux


You can use the following extension method:

public static class RazorEngineServiceExtensions {
    public static bool IsTemplateCached(this IRazorEngineService service, string name, Type modelType);
}

An example:

if (!Engine.Razor.IsTemplateCached(templateName, modelType)) {
    Engine.Razor.Compile(templateSource, templateName, modelType);
}
like image 42
UserControl Avatar answered Oct 02 '22 09:10

UserControl