Theme settings in the layout view

Topics: Writing themes
Oct 26, 2012 at 2:06 PM

I'm writing a theme, containing some back-end settings and everything works great.

I load the settings from a custom service, and are returning a record directly from the database (maybe it should be cached, but this works for now) like this:

    /* Load Theme settings */
    var settings = WorkContext.Resolve<MyTheme.Services.ISettingsService>().GetSettings();

My issue is, that I do this directly in the layout.cshtml file - and I don't like that approach. I just can't figure out the right way to do it.

Is there a smarter way of passing the ThemeSettingsPartRecord (or a viewmodel of this) to the layout view in a theme?

Oct 26, 2012 at 2:40 PM

One way to do it is to use a FilterProvider to attach site settings data to the Layout shape. This is untested in a theme, but it is a modified version of code I'm using in a module: 

    public class LayoutFilter : FilterProvider, IResultFilter {
        private readonly IWorkContextAccessor _wca;
        dynamic Shape { get; set; }


        public LayoutFilter(
            IWorkContextAccessor wca
            , IShapeFactory shapeFactory
        ) {
            _wca = wca;
            Shape = shapeFactory;
        }

        public void OnResultExecuting(ResultExecutingContext filterContext) {
            WorkContext workContext = _wca.GetContext();
            workContext.Layout.Metadata.Settings = MyTheme.Services.ISettingsService>().GetSettings(); 
        }
    }

Oct 26, 2012 at 2:59 PM

Putting Settings it in "Layout.Metadata" throws an error about there is no "Settings" in the Metadata shape (or something like that, whatever), but it pointed me in the right direction! I modified your code a bit, and now it's working like a charm! Thanks a lot.

The filter now looks like this:

    public class LayoutFilter : FilterProvider, IResultFilter {
        private readonly IWorkContextAccessor _workContextAccessor;
        private readonly ISettingsService _settingsService;
        dynamic Shape { get; set; }

        public LayoutFilter(IWorkContextAccessor workContextAccessor, 
            ISettingsService settingsService,
            IShapeFactory shapeFactory) {
                _workContextAccessor = workContextAccessor;
                _settingsService = settingsService;
                Shape = shapeFactory;
        }

        public void OnResultExecuting(ResultExecutingContext filterContext) {
            WorkContext workContext = _workContextAccessor.GetContext();
            workContext.Layout.Settings = _settingsService.GetSettings();
        }

        public void OnResultExecuted(ResultExecutedContext filterContext) { }
    }

 

And from the view, I simply use following code:

    /* Load Theme settings */
    SettingsRecord settings = WorkContext.Layout.Settings;