asp.net mvc 使用nvelocity替换razor

时间:2022-11-24 18:25:04

看清楚标题呀 是nvelocity替换razor

背景

我也不知道出于什么考虑,可能是老大说后期要弄到java平台上 然后视图页不要用Razor了。所以就让我用Nvelocity去替换原有的razor。

简单实现

  • 创建一个引擎管理类
 public class VelocityManager
    {
        public static VelocityManager Instance;

        public VelocityEngine Engine;

        static VelocityManager()
        {
            Instance = new VelocityManager();
        }

        private VelocityManager()
        {
            Engine = new VelocityEngine();
            Engine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/");
            Engine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, baseDirectory + "/Views");
            Engine.Init();
        }
    }
  • 创建视图类
  public class NVelocityView : IView
    {
        private string viewPath;
        public NVelocityView(string viewPath)
        {
            this.viewPath = viewPath.Replace("~/Views", "/");
        }
        public void Render(ViewContext viewContext, TextWriter writer)
        {
            RouteData data = viewContext.Controller.ControllerContext.RouteData;

            Template vltTemplate = VelocityManager.Instance.Engine.GetTemplate(viewPath);
            VelocityContext vltContext = new VelocityContext();
            vltContext.Put("control", viewContext.ViewBag.control ?? new object());
            vltTemplate.Merge(vltContext, writer);

        }
    }
  • 创建引擎类
 public class NVolocityViewEngine : BuildManagerViewEngine
    {
        public NVolocityViewEngine() : base()
        {
            ViewLocationFormats = new[]
            {
                "~/Views/{1}/{0}.cshtml",
                "~/Views/Shared/{0}.cshtml",
                "~/CustomViewLocation/{1}/{0}.cshtml",
                "~/CustomViewLocation/{1}/{0}.vm"
            };
        }
           protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            return new NVelocityView(partialPath);
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            return new NVelocityView(viewPath);
        }
    }
  • 在Global.asax中清楚原有引擎 添加自己的即可
 protected void Application_Start()
        {
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new NVolocityViewEngine());

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

        }