Jx.Cms开发笔记(三)-Views主题动态切换

效果展示

我们可以在后台动态切换主题

theme.png

目前Jx.Cms有两个主题,其中一个是默认主题,另一个是仿的Blogs主题。

我们可以通过点击启用按钮来动态切换两个主题。

default.pngblogs.png

实现方法

首先写一个实现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" };

这里的内容,就可以到对应的主题下获取内容了。

posted @   jvx  阅读(1294)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示