4

I've seen a lot of people that like using the NHaml View Engine in ASP.NET MVC, but I'm wondering if NHaml can be used as a general purpose templating engine in .NET ? I'd like to use NHaml from a Console application, or to generate HTML email templates, outside of the ASP MVC View Engine environment. Is this possible? I haven't found many code examples anywhere showing how to do this. Thanks!

Kevin Southworth
  • 373
  • 2
  • 11
  • Apparently Razor the new view engine in MVC 3 can be used standalone without ASP.NET for the very things you describe. So it'll depend on how loosely coupled NHaml is with the ASP.NET runtime. – John Mills Dec 08 '10 at 04:41
  • Elaborate your question if my answer do not help. – jgauffin May 25 '12 at 08:28

2 Answers2

4

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);
jgauffin
  • 99,844
  • 45
  • 235
  • 372
0

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);
Igor
  • 5,750
  • 2
  • 16
  • 7