Search
Back to all

Custom View Engine

Plugin Code 

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Razor;

using Nop.Core;
using Nop.Core.Infrastructure;
using Nop.Services.Configuration;

using Nop.Web.Framework.Themes;
using Nop.Web.Framework;

namespace Nop.Plugin.Apollo.Appointments.ViewEngine
{
    public class CustomViewEngine : IViewLocationExpander
    {
        public string StoreTheme = "DefaultClean";

        public void PopulateValues(ViewLocationExpanderContext context)
        {
            //no need to add the themeable view locations at all as the administration should not be themeable anyway
            if (context.AreaName?.Equals(AreaNames.Admin) ?? false)
                return;

            var settingService = EngineContext.Current.Resolve<ISettingService>();
            var storeContext = EngineContext.Current.Resolve<IStoreContext>();

            StoreTheme = settingService.GetSettingByKeyAsync("storeinformationsettings.defaultstoretheme", "DefaultClean", storeContext.GetCurrentStore().Id, true).Result;

            context.Values[StoreTheme] = EngineContext.Current.Resolve<IThemeContext>().GetWorkingThemeNameAsync().Result;
        }

        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {

            if (context.AreaName == null)
            {
                if (!context.Values.TryGetValue(StoreTheme, out string? theme))
                    return viewLocations;

                if (context.ViewName == "_AddToCart" &&
                   (context.ControllerName == "Product" || context.ControllerName == "YourController"))
                {
                    viewLocations = new[] { $"~/Plugins/SSI.Plugin.Name/Views/FrontView/Shared/Themes/_AddToCart.cshtml" }.Concat(viewLocations);
                }

            }

            return viewLocations;
        }
    }
}

Add to the Plugin Startup File

 

public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
    services.Configure<RazorViewEngineOptions>(o =>
    {
        o.ViewLocationExpanders.Add(new CustomViewEngine());
    });
}
Comments
Leave your comment Close