View/Filter Modes

What would be the best way to implement different view/sort modes for a given page? I have a list of items that I want to be able to display in grid/list view, and sort by most popular/most recent.

I could just build different templates each permutation, but that would result in a lot of repeated code. Is there a better way to do this?

Perhaps you want to try URL queries to pass the sorting method to your template by the users browser. Then your template has a switch case to generate the collection of pages depending of the parameters given in to it.

If you want to switch modes from other templates, I would move the code to a snippet and give parameters to the snippet.

snippet('get_articles', array('sort_method'=>'popular', 'root'=>$page));

or something like this. You can access the parameter simply by $sort_method.

This is the way I use in my projects to have one piece of code with slightly different behavior.
P.S. you must give it the “root” to work the same as a template. Simply change $page to $root (in my example), because the snippet has no current page.