Toggle between grid and list view in within template

Hello,

my /procjects overview template (projects.php) makes use of two snippets,

<?php snippet('gridview') ?>

and

<?php snippet('listview') ?>

How can I let the user toggle between these different view modes (grid OR list) from the frontend, ideally without changing the URL (should be domain.com/projects no matter if in grid or in list mode), or using a different template?

Many thanks in advance!

Two options at least, I think:

  • Load both snippets and hide one on load, then toggle via JS.
  • Make an Ajax call when the button is clicked. If you want to store settings between visits, use a cookie or localstorage to store them.

Maybe you can even make them so that you only need to swap classes instead of the complete markup?

Thanks for the hints @texnixe

The pure js toggle does not work so well as I’m loosing the state as soon as the user applies a filter (e.g. project/tag:sometag), so maybe ajax + cookie it is.

Still, I was wondering if there’s also a non-javascript solution?

With PHP you would have to use a submit button and reload the page. In your controller, you would check if the cookie exists and depending on its value, deliver the corresponding snippet.

I see – you’re right.

Maybe it is a better option to have a dedicated section / template after all, so the user can switch between a projects and a projectslist section; seems to be the only way that works “hands-on”, even as a “static” link – IMO a big advantage to a cookie-based solution.

The alternative to a completely different URL would be to use a parameter