Theming views to create a mobile version

August 21, 2011

I’ve started work on building a mobile version of The Gallery Guide, my pet Drupal project. The main site has been built to be very visual - it’s got a lot of images, Google map embeds, and most of all, it’s got a lot of views. Pretty much the whole site is built on Views.

The Mobile tools module has made the whole thing pretty easy to set up - a couple of hours tinkering and I had a usable mobile site with

When I started looking at the mobile version, I soon realised that all those images just wouldn’t work on small screens, and grid views would need to be reworked as lists. The thought of rebuilding all my views filled me with dread, even if there is a clone function. It would make the navigation really complicated, too.

The lazy way would be CSS display:none, but that would be a massive waste of bandwidth.

Then I realised I could just theme the problems away. I copied views-view-fields to my mobile theme, and just added an if statement to stop certain fields from being output.

<?php
$hidden_fields = array(
    'field-images-fid'
);
?>

<?php foreach ($fields as $id => $field): ?>
    <?php if (!empty($field->separator)): ?>
      <?php print $field->separator; ?>
    <?php endif; ?>


    <?php if(!in_array($field->class, $hidden_fields)):?>
      <<?php print $field->inline_html;?> class="views-field-<?php print $field->class; ?>">
        <?php if ($field->label): ?>
          <label class="views-label-<?php print $field->class; ?>">
            <?php print $field->label; ?>:
          </label>
        <?php endif; ?>
        <?php
          // $field->element_type is either SPAN or DIV depending upon whether or not
          // the field is a 'block' element type or 'inline' element type.
          ?>
          <<?php print $field->element_type; ?> class="field-content">
            <?php print $field->content; ?>
          </<?php print $field->element_type; ?>>
      </<?php print $field->inline_html;?>>
  <?php endif; ?>

<?php endforeach; ?>

To turn the grid views back into unformatted views, I over-rode views-view-grid.tpl.php to get rid of any mention of tables:

<?php if (!empty($title)) : ?>
    <h3><?php print $title; ?></h3>
<?php endif; ?>

<?php foreach ($rows as $row_number => $columns): ?>
    <?php foreach ($columns as $column_number => $item): ?>
        <div class="<?php print 'col-' . ($column_number + 1); ?>">
            <?php print $item; ?>
        </div>
   <?php endforeach; ?>
<?php endforeach; ?>