How to Build a Custom View Engine with Theme Support

added by mceranski
5/17/2010 9:49:56 PM

0 Kicks, 202 Views

In case you don’t know, the developers of ASP.NET MVC went to great lengths to make their framework completely flexible. By default, when you create a new MVC project you are using the Web Forms view engine. However, you can rip out the default view engine and register your own. As a matter of fact, there are already a variety of view engines available to us: * Spark – The Spark view engine claims to be HTML friendly and uses the philosophy of less is more. I wrote an article about the Spark view engine before Louis Desjardin accepted a job with Microsoft. * NHaml - Contributed by Andrew Peters. NHaml provides an internal DSL for XHTML. * NVelocity - Adapted by Hammet and added to MvcContrib with permission. * Brail. The Brail view engine from MonoRail has been ported to ASP.NET MVC and added to MvcContrib. This view engine lives in MonoRail, but with MvcContrib, it can now be used with ASP.NET MVC Framework controllers. Ported by Bill Pierce. * XSLT - Contributed by Ivan Porto. Since the view engines listed above are open source it was easy to find code to tailor my custom view engine after. In addition, I also found a great article titled Creating Your First MVC ViewEngine by Nick Berardi. In any case, the first step in creating a view engine is defining your search locations. If you have been working with MVC for any length of time, then you know that MVC uses a series of search paths when finding a view. So if you have a view named Index in your Post controller, MVC will look first in the Views\Post folder for the Index.aspx file. If it is not found there, then the Web Forms view engine will look in the Views\Shared folder for the view. Since we are trying to implement themes we have a few more locations that we want MVC to search in. These would be \Themes\{SomeTheme}\Views\Post and \Themes\{SomeTheme}\Shared. In order to add these new search locations we need to set the MasterLocationFormats, ViewLocationFormats and PartialLocationFormats in the constructor of our custom view engine...


0 comments