Skip to content

Instantly share code, notes, and snippets.

@theuntitled
Created December 2, 2014 18:29
Show Gist options
  • Save theuntitled/659a4275526b79d7a62b to your computer and use it in GitHub Desktop.
Save theuntitled/659a4275526b79d7a62b to your computer and use it in GitHub Desktop.
.NET MVC 5 Themed Partial Extension Method
@using ProjectName.Extensions
@Html.ThemePartial( "WelcomeMessage" )
@html.ThemePartial( "SomeCopyText" )
<p>Text that does not need to be themed</p>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace ProjectName.Extensions {
/// <summary>
/// Extends the default HtmlHelper class for theme related methods
/// </summary>
public static class ThemeHtmlExtensions {
/// <summary>
/// Renders a themed partial view, falls back to no theme if no partial exists for the theme
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="partialViewName"></param>
/// <returns></returns>
public static MvcHtmlString ThemePartial( this HtmlHelper htmlHelper , string partialViewName ) {
var controllerName = htmlHelper.ViewContext.RouteData.GetRequiredString( "controller" );
var themeName = ConfigurationManager.AppSettings.Get( "Theme" ) ?? "Theme";
var pathsToSearch = new List<string>();
var possibleExtensions = new List<string> {
"aspx" ,
"ascx" ,
"cshtml" ,
"vbhtml" ,
};
foreach ( var extension in possibleExtensions ) {
pathsToSearch.Add( string.Format( "~/Views/Shared/{0}.{1}.{2}" , partialViewName , themeName , extension ) );
pathsToSearch.Add(
string.Format( "~/Views/{0}/{1}.{2}.{3}" , controllerName , partialViewName , themeName , extension ) );
pathsToSearch.Add( string.Format( "~/Views/Shared/{0}.{1}" , partialViewName , extension ) );
pathsToSearch.Add( string.Format( "~/Views/{0}/{1}.{2}" , controllerName , partialViewName , extension ) );
}
// TODO: Extend for areas
var path = pathsToSearch.FirstOrDefault( query => File.Exists( HostingEnvironment.MapPath( query ) ) );
if ( string.IsNullOrEmpty( path ) ) {
throw new InvalidOperationException(
string.Format(
"The themed partial view '{0}' was not found or no view engine supports the searched locations. The following locations were searched:{1}{2}" ,
partialViewName ,
Environment.NewLine ,
string.Join( Environment.NewLine , pathsToSearch ) ) );
}
return htmlHelper.Partial( path );
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
...
<appSettings>
<add key="Theme" value="MyTheme" />
</appSettings>
...
</configuration>
<h1>Default Welcome!</h1>
<h1>Themed Welcome!</h1>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment