NHaml可以用作通用模板引擎吗? (MVC之外)

时间:2010-12-08 03:54:59

标签: .net template-engine nhaml

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);
相关问题