Search code examples
razortemplate-enginerazor-2

Rendering an email throws a TemplateCompilationException using RazorEngine 3 in a non-MVC project


I am trying to render emails in a windows service host.

I use RazorEngine 3 forked by coxp which has support for Razor 2. https://github.com/coxp/RazorEngine/tree/release-3.0/src

This works fine for a couple of emailtemplates but there is one causing me problems.

@model string

<a href="@Model" target="_blank">Click here</a> to enter a new password for your account.

This throws a CompilationException: The name 'WriteAttribute' does not exist in the current context. So passing in a string as model and putting it in the href-attribute causes problems.

I can make it work by changing this line by:

@Raw(string.Format("<a href=\"{0}\" target=\"_blank\">Klik hier</a>.", @Model))

but this makes the template very unreadable and harder to pass along to a marketing department for further styling.

I like to add that referencing the RazorEngine by using a Nuget package is not a solution since it is based on Razor 1 and somewhere along the process the DLL for system.web.razor gets replaced by version 2 which breaks any code using RazorEngine. It seems more interesting to use Razor 2 to benefit from the new features and to be up to date.

Any suggestions on how to fix this would be great. Sharing your experiences is also very welcome.

UPDATE 1

It seems like calling SetTemplateBaseType might help, but this method does not exist anymore, so I wonder how to be able to bind the templatebasetype?

//Missing method in the new RazorEngine build from coxp.
Razor.SetTemplateBaseType(typeof(HtmlTemplateBase<>));

Solution

  • I use Windsor to inject the template service rather than using the Razor object. Here is a simplified part of the code that shows how to set the base template type.

        private static ITemplateService CreateTemplateService()
        {
            var config = new TemplateServiceConfiguration
                             {
                                 BaseTemplateType = typeof (HtmlTemplateBase<>),
                             };
            return new TemplateService(config);
        }