The easiest way with Javascript would be to return both templates with PHP, in a containing element, and then show/hide them on a click event.
<div id="grid">
grid template here
</div>
<div id="list">
list template here
</div>But, that's pretty inefficient, since you're doubling the amount of data you're returning to the browser. Another way is to return JSON or something, and format it into your templates with Javascript.
If you don't want to use Javascript, your PHP logic is basically as such:
$view = 'grid';
if (isset($_GET['view'])) {
$view = $_GET['view'];
}
if ($view == 'grid') {
// return grid template
} else {
// return list template
}