2013-01-03 38 views
2

我试图在Windows服务主机中呈现电子邮件。渲染电子邮件在非MVC项目中使用RazorEngine 3引发TemplateCompilationException

我用coxp分叉RazorEngine 3这对于剃刀2. https://github.com/coxp/RazorEngine/tree/release-3.0/src

也能正常工作的一对夫妇emailtemplates的支持,但有一个引起我的问​​题。

@model string 

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

这会引发CompilationException:名称'WriteAttribute'在当前上下文中不存在。所以传入字符串作为模型并将其放入href-attribute会导致问题。

我可以把它通过改变这一行工作:

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

但是这使得模板非常不可读,更难沿到营销部门作进一步的造型传递。

我想补充一点,使用Nuget包引用RazorEngine不是一个解决方案,因为它基于Razor 1,并且在进程的某个地方,system.web.razor的DLL被替换为版本2的DLL,该代码打破了任何代码使用RazorEngine。使用Razor 2从新功能中获益并使其更新似乎更有趣。

关于如何解决这个问题的任何建议都会很好。分享您的经验也非常受欢迎。

更新1

好像叫SetTemplateBaseType可能有帮助,但这种方法不存在了,所以我不知道如何能够在templatebasetype绑定?

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

回答

4

我使用Windsor注入模板服务而不是使用Razor对象。以下是代码的简化部分,显示了如何设置基本模板类型。

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

完美的作品!非常感谢。 –

0

RazorEngine 3.1.0

点点修改例如基于coxp答案没有注射:

private static bool _razorInitialized; 

    private static void InitializeRazor() 
    { 
     if (_razorInitialized) return; 
     _razorInitialized = true; 
     Razor.SetTemplateService(CreateTemplateService()); 
    } 

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

    public static string ParseTemplate(string name, object model) 
    { 
     InitializeRazor(); 

     var appFileName = "~/EmailTemplates/" + name + ".cshtml"; 
     var template = File.ReadAllText(HttpContext.Current.Server.MapPath(appFileName)); 
     return RazorEngine.Razor.Parse(template, model); 
    } 
相关问题