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");
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
).
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With