Add bootstrap CSS classes to images through template.php

How is possible to add .img-responsive class by default on images with Drupal?

Bootstrap Framework provides CSS classes for responsive-friendly images (.img-responsive), or rounded images (.img-rounded), tumbnail (.img-thumbnail) and even circle images (.img-circle) (source: http://getbootstrap.com/css/#images).

How is possible to add .img-responsive class by default on images with Drupal?

jQuery solution

One of the solution will be to use jQuery to add the img-responsive class into images with the addClass property.  For example :

$('img').addClass('img-responsive');

Well, this is not the best solution.

Using template.php file

A preprocess function in template.php can be used to add the CSS class.

 

Add the class on all images by default

<?php /**  *  */
   function THEMENAME_preprocess_image_style(&$vars) {        
     $vars['attributes']['class'][] = 'img-responsive'; 
     // http://getbootstrap.com/css/#overview-responsive-images
​   }
?>

Don't forget to clear the cache after that! (admin/config/development/performance)

In that case, all images will have the img-responsive class.

 

Add the class on specific field

You can also add the img-responsive class to a specific field.


<?php
   function THEME_preprocess_field(&$variables) {    
      if($variables['element']['#field_name'] == 'field_photo'){        
          foreach($variables['items'] as $key => $item){            
             $variables['items'][ $key ]['#item']['attributes']['class'][] = 'img-responsive';
             // http://getbootstrap.com/css/#overview-responsive-images        
          }    
       }
    }
​?>

 

Add the class on specific image style

You can also add the img-responsive class to a specific style of images. Which means that you created a new image style (admin/config/media/image-styles) and through template.php you assign the img-responsive class to this specific style.


<?php
   function THEME_preprocess_image_style(&$vars) {     
      if($vars['style_name'] == 'MYSTYLE'){            
         $vars['attributes']['class'][] = 'img-responsive'; 
         // http://getbootstrap.com/css/#overview-responsive-images        
      }
   }
?>

Every time that you add a few lines of code into template.php, don't forget to "clear cache" (admin/config/development/performance) !

(source: https://www.drupal.org/node/2169157)