4

我见过很多人喜欢在 ASP.NET MVC 中使用 NHaml 视图引擎,但我想知道 NHaml 是否可以用作 .NET 中的通用模板引擎?我想从控制台应用程序中使用 NHaml,或者在 ASP MVC 视图引擎环境之外生成 HTML 电子邮件模板。这可能吗?我在任何地方都没有找到很多代码示例来展示如何做到这一点。谢谢!

4

2 回答 2

4

是的,它可以在没有 ASP.Net MVC 的情况下使用。我将它用于我自己的 Web 服务器(但这并不意味着您必须将它与 Web 服务器一起使用)。

看看我在这里如何使用它: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);
于 2010-12-08T06:33:50.033 回答
0

最新的 NHaml 使其更容易:

    var te = XmlConfigurator.GetTemplateEngine("nhaml.config");

    var ct = te.GetCompiledTemplate(new FileViewSource(new FileInfo("period.nhaml")), typeof(Template));

    var template = ct.CreateTemplate();

    var viewData = new Dictionary<string,object>();

    template.ViewData = viewData;

    template.Render(writer);
于 2015-06-24T02:56:41.863 回答