Can NHaml be used as a general purpose template engine? (outside of MVC)

前提是你 提交于 2019-12-01 19:53:13

Yes, it can be used without ASP.Net MVC. I use it for my own web server (but that doesn't mean that you HAVE to use it with web servers).

Check out how I use it here: http://webserver.codeplex.com/SourceControl/changeset/view/50874#671672

What you do in short is something like this:

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);

Latest NHaml makes it easier:

    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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!