Jx.Cms开发笔记(三)-Views主题动态切换
效果展示
我们可以在后台动态切换主题

目前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" };这里的内容,就可以到对应的主题下获取内容了。

浙公网安备 33010602011771号