adoconnection / RazorEngineCore

.NET6 Razor Template Engine
MIT License
576 stars 85 forks source link

Add support for compiling and running sets of templates #29

Closed Merlin04 closed 10 months ago

Merlin04 commented 4 years ago

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)\n@Greeting.GetGreeting(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.

adoconnection commented 4 years ago

Hi, is there any actual difference between having one assembly with several templates and several assemblies with one template?

Merlin04 commented 4 years ago

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.

adoconnection commented 10 months ago

I will close this PR as its a perfect candidate for extension method similar to https://github.com/adoconnection/RazorEngineCore/wiki/@Include-and-@Layout