Skip to content

Instantly share code, notes, and snippets.

@g0t4
Last active August 29, 2015 13:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save g0t4/8741285 to your computer and use it in GitHub Desktop.
Save g0t4/8741285 to your computer and use it in GitHub Desktop.
Hack to set a custom base view with Nancy and Razor
// At this time Nancy's Razor view engine doesn't let you set a default base class like ASP.NET web pages does with pageBaseType, if you want to hack one in here is how:
// First create your custom type, this one writes out hack for everything, so obviously remove that unless you want that :)
public abstract class MyRazorPage<T> : NancyRazorViewBase<T>
{
public override void Write(object value)
{
base.WriteLiteral("hack");
}
}
public abstract class MyRazorPage : MyRazorPage<dynamic>
{
}
// Extend the default RazorViewEngine for Nancy:
public class HackedRazorViewEngine : RazorViewEngine
{
public HackedRazorViewEngine(IRazorConfiguration configuration) : base(configuration)
{
var viewRenderers = typeof (RazorViewEngine).GetField("viewRenderers", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this) as IEnumerable<IRazorViewRenderer>;
viewRenderers.ToList().ForEach(r => r.Host.DefaultBaseClass = typeof (MyRazorPage).FullName);
}
}
// this just goes through each view renderer and sets the DefaultBaseClass to your type, of course if internal implementation details change this code could break as viewRenderers are private
// Then in your Nancy boostrapper, override the ViewEngines:
protected override IEnumerable<Type> ViewEngines
{
get
{
return base.ViewEngines
.Where(e => e != typeof (RazorViewEngine));
}
}
// this just removes the default RazorViewEngine, HackedRazorViewEngine will be scanned in automatically by Nancy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment