我见过很多人喜欢在 ASP.NET MVC 中使用 NHaml 视图引擎,但我想知道 NHaml 是否可以用作 .NET 中的通用模板引擎?我想在 ASP MVC 视图引擎环境之外从控制台应用程序使用 NHaml,或者生成 HTML 电子邮件模板。这可能吗?我没有在任何地方找到很多代码示例来展示如何执行此操作。谢谢!
是的,它可以在没有 ASP.Net MVC 的情况下使用。我将它用于我自己的网络服务器(但这并不意味着您必须将它与网络服务器一起使用)。
在这里查看我如何使用它:http://webserver.codeplex.com/SourceControl/changeset/view/50874#671672
简而言之,你所做的就是这样的:
TemplateEngine _templateEngine = new TemplateEngine();
// Add a type used in the template. Needed to that nhaml can find it when compiling the template
_templateEngine.Options.AddReferences(typeof (TypeInYourAssembly));
// base class for all templates
_templateEngine.Options.TemplateBaseType = typeof (BaseClassForTemplates);
//class providing content to the engine, should implement ITemplateContentProvider
_templateEngine.Options.TemplateContentProvider = this;
// compile the template,
CompiledTemplate template = _templateEngine.Compile(new List<string> {layoutName, viewPath},
typeof (TemplateImplementation));
//create a instance
var instance = (NHamlView)template.CreateInstance();
// provide the view data used by the template
instance.ViewData = viewData;
// render it into a text writer
instance.Render(writer);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)