Skip to content

Instantly share code, notes, and snippets.

@richiejp
Created January 10, 2012 12:36
Show Gist options
  • Save richiejp/1588836 to your computer and use it in GitHub Desktop.
Save richiejp/1588836 to your computer and use it in GitHub Desktop.
NHaml adapter for Nancy framework hack
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Nancy;
using Nancy.ViewEngines;
using Nancy.Responses;
using NHaml4.Walkers.CodeDom;
using NHaml4.TemplateResolution;
using NHaml4.TemplateBase;
using NHaml4;
using System.IO;
using System.Text;
namespace Nancy.ViewEngines.NHaml
{
public class NHamlViewEngine : IViewEngine
{
private TemplateEngine engine;
private FileTemplateContentProvider contentp;
public IEnumerable<string> Extensions
{
get { return new string[] { "haml", "nhaml" }; }
}
public void Initialize(ViewEngineStartupContext viewEngineStartupContext)
{
engine = new TemplateEngine(new HamlOptions());
contentp = new FileTemplateContentProvider();
}
private Template getTemplate(ViewLocationResult vlr, IRenderContext rc)
{
var source = new NancyNHamlViewSource(vlr, rc);
var tmplt = engine.GetCompiledTemplate(source);
return tmplt.CreateTemplate();
}
public Response RenderView(
ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
{
return new HtmlResponse
{
Contents = strm =>
{
var wrtr = new StreamWriter(strm);
getTemplate(viewLocationResult, renderContext).Render(wrtr);
wrtr.Flush();
return;
}
};
}
}
class NancyNHamlViewSource : IViewSource
{
private ViewLocationResult vlr;
private IRenderContext rc;
public NancyNHamlViewSource(ViewLocationResult vlr, IRenderContext rc)
{
this.vlr = vlr;
this.rc = rc;
}
public string GetClassName()
{
return vlr.Location + "_" + vlr.Name;
}
public StreamReader GetStreamReader()
{
return new StreamReader(new MemoryStream(new UTF8Encoding().GetBytes(vlr.Contents().ReadToEnd())));
}
public bool IsModified
{
get { return true; }
}
public string Path
{
get { throw new NotImplementedException(); }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment