效果展示
我們可以在后台動態切換主題
目前Jx.Cms有兩個主題,其中一個是默認主題,另一個是仿的Blogs主題。
我們可以通過點擊啟用按鈕來動態切換兩個主題。
實現方法
首先寫一個實現IViewLocationExpander
接口的類,我這里命名為TemplateViewLocationExpander
.
public class TemplateViewLocationExpander : IViewLocationExpander
{
public void PopulateValues(ViewLocationExpanderContext context)
{
context.Values["template"] = ThemeUtil.GetThemeName();
}
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
if (!context.AreaName.IsNullOrEmpty())
{
return viewLocations;
}
var themeName = context.Values["template"] ?? ThemeUtil.PcThemeName;
string[] locations = { "/Pages/" + themeName + "/{1}/{0}.cshtml", "/Pages/" + themeName + "/{0}.cshtml", "/Pages/" + themeName + "/Shared/{0}.cshtml", "/Pages/Shared/{0}.cshtml" };
return locations.Union(viewLocations.Where(x => !x.StartsWith("/Views/")));
}
}
首先我們在PopulateValues
中給context.Values
設置一個值,context.Values
是一個字典,所以我們可以在里面加一個template
的key,如果在PopulateValues
中context有變化,就會走到ExpandViewLocations
方法中。
在ExpandViewLocations
中,我們首先把有Area的去除,因為Area內肯定不是我們的主題。
然后查找
string[] locations = { "/Pages/" + themeName + "/{1}/{0}.cshtml", "/Pages/" + themeName + "/{0}.cshtml", "/Pages/" + themeName + "/Shared/{0}.cshtml", "/Pages/Shared/{0}.cshtml" };
這里的內容,就可以到對應的主題下獲取內容了。