Make Drupal "Views Grid Style" Responsive with Bootstrap

Mohammed J. Razem

You probably used the Views' famous Grid Style Format to easily output items in a grid. You also probably noted that the Grid Style Format uses tables, which is not responsive, and is does not play well with Twitter's Bootstrap UI library.

Here's a quick hack override to make your favorite Grid Style Format, responsive and play well without any need for extra CSS.

 

What is the trick?

 

Easy! The whole purpose is to replace the html tags in views-view-grid.tpl.php to us <div> instead of <table>, and Bootstrap's grid instead of <tr> and <td>.

 

How this is done?

 

  1. Override views-view-grid.tpl.php in your theme with the code below.
  2. Make sure you choose the Grid Style Format from your view format settings.
<?php if (!empty($title)) : ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<div class="<?php print $class; ?>"<?php print $attributes; ?>>
  <?php if (!empty($caption)) : ?>
    <caption><?php print $caption; ?></caption>
  <?php endif; ?>

  <div>
    <?php foreach ($rows as $row_number => $columns): ?>
      <?php
        $columns_count = count($columns);
        $span_number = round(12 / $columns_count);
       ?>
      <div <?php if ($row_classes[$row_number]) { print 'class="row-fluid ' . $row_classes[$row_number] .'"';  } ?>>
        <?php foreach ($columns as $column_number => $item): ?>
          <div <?php if ($column_classes[$row_number][$column_number]) { print 'class="span' . $span_number . ' ' . $column_classes[$row_number][$column_number] .'"';  } ?>>
            <?php print $item; ?>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endforeach; ?>
  </div>
</div>