Dynamically changing between list and grid view


#1

I have two buttons to switch between a list and a grid view, showing users. Right now, the switch happens by the use of jQuery, adding classes and floats to existing divs. As this isn’t a really clean solution, I’m wondering if it’s possible to do this in some sort of “Ember way” by having two different erb partials, both showing the same content but in a different way, which can be exchanged against each other by the press of a button.


#2

The forthcoming Query Param’s is your best option. That way you can use link-to’s for the buttions that will also give you active state class.

App.WhateverController = Ember.ArrayController.extend({
    queryParams: ['layout'],
    layout: 'list', // default
    viewList: Ember.computed.equal('layout', 'list'),
    viewGrid: Ember.computed.equal('layout', 'grid')
});

Template Option A

{{link-to 'List View' (layout='list')}}
{{link-to 'Grid View' (layout='grid')}}

{{#if viewList}}
    {{partial 'whatever.list'}}
    {{!-- or just your list code.. --}}
{{/if}}

{{#if viewGrid}}
    {{partial 'whatever.grid'}}
    {{!-- or just your grid code.. --}}
{{/if}}

Template Option B: Or just look for one type and provide default, in case the user types ?layout=dlkfa

{{link-to 'List View' (layout='list')}}
{{link-to 'Grid View' (layout='grid')}}

{{#if viewGrid}}
    {{partial 'whatever.grid'}}
    {{!-- or just your grid code.. --}}
{{else}}
    {{partial 'whatever.list'}}
    {{!-- or just your list code.. --}}
{{/if}}

An even simpler option is to just use the layout property in the {{partial}} helper, as shown in the QP example. However, that doesn’t provide a “default view” in case the user types in something weird.


#3

Thank you so much for your answer and the detailed example.


#4

Great answer. I’m new to Ember and I’m curious, how would you do this now given that Controllers are deprecated?


#5

I’d suggest using components for this now:

{{if gridView}}
    {{my-component/grid data=data}}
{{else}}
    {{my-component/list data=data}}
{{/if}}

Or even better:

{{component (if gridView "my-component/grid" "my-component/list") data=data}}

And in you my-component.js you can have the following:

export default Ember.Component.extend({
    gridView: false // default,

    actions: {
        toggleView() {
            this.toggleProperty('gridView');
        }
    }
});

#6

Thanks! Looks much cleaner.