Using Antaris RazorEngine, given two strings:
a Razor template without a layout specified
<h1>My template</h1>
and a layout in which it should be rendered
<html>RenderBody()</html>
I would like to be able to parse/compile the strings and set the layout in the code performing the parsing. Something like:
ParseWithTemplate(templateAsString, layoutAsString, model, etc.);
How might I implement this ParseWithTemplate(String, String, ...)
method?
Background: I'm building a static site generator and want a way to provide a default layout so I don't have to specify it in every single one of my many site pages. It should be possible to override the default if a Layout = "layoutName"
is provided in the template.
If you pre-compile the layout template, you should be able to set the Layout directly by casting the template to TemplateBase. If you later specify the Layout in the template markup, this will override the value in the code as you require when the template executes.
ITemplateService templateService = ...;
// Ensure layout template is cached with layoutCacheName
templateService.GetTemplate(layoutAsString, model, layoutCacheName);
ITemplate template = templateService.GetTemplate(templateAsString, model, templateCacheName);
var templateBase = template as TemplateBase;
if (templateBase != null) templateBase.Layout = layoutCacheName;