RazorEngineCore
RazorEngineCore copied to clipboard
Add support for compiling and running sets of templates
This PR adds support for compiling and running sets of templates. An example of how this works can be seen in the test TestCompileAndRun_Set:
public void TestCompileAndRun_Set()
{
RazorEngine razorEngine = new RazorEngine();
IRazorEngineCompiledTemplateSet templateSet = razorEngine.CompileSet(new Dictionary<string, string>
{
{ "Template1", "@Template2.GetGreeting(Model.Name)\[email protected](Model.Name)" },
{ "Template2", @"
Hello!
@functions {
public static string GetGreeting(string name)
{
return ""Hello, "" + name + ""!"";
}
}
" }
}, builder => { builder.Options.TemplateNamespace = "Testing"; }, new List<string>
{
@"
namespace Testing
{
public static class Greeting
{
public static string GetGreeting(string name)
{
return ""Hello, "" + name + ""!"";
}
}
}
"
});
string actual = templateSet.Run("Template1", new {Name = "Alex"});
Assert.AreEqual("Hello, Alex!\nHello, Alex!", actual);
}
Both Template1 and Template2 are compiled into the same assembly/IRazorEngineCompiledTemplateSet, and the template to run can be selected by its class name (set in the dictionary of template sources). In addition, you can provide a list of strings to CompileSet that contain C# code which will be included in the assembly.
Hi, is there any actual difference between having one assembly with several templates and several assemblies with one template?
Yes, if you define methods in one template you can access them in another. There also should be a performance gain when compiling multiple templates in one assembly vs multiple templates in multiple assemblies.
I will close this PR as its a perfect candidate for extension method similar to https://github.com/adoconnection/RazorEngineCore/wiki/@Include-and-@Layout