1

I am trying to add different html class attributes to images based on what view they are being output with. I have created two image styles using the administrative interface, here are the two machine names.
1. front_page_recent_blogs
2. blog_page_view

I have assigned each of these to the image field in the two different views. I have successfully added classes to the front_page_recent_blogs images using the following code:

function mythemename_image_style($variables) {

  $variables['attributes'] = array(
    'class' => 'img-responsive center-block',
  );

  $variables['path'] = image_style_url('front_page_recent_blogs', $variables['path']);
  return theme('image', $variables);

}

How do I add classes to the blog_page_view image style, and to any future image styles? Calling the function twice breaks the entire site. If there is a better way to add classes to multiple image styles than overriding theme_image_style, please let me know.

0

For this situation overwriting the image_style theme function seems a bit heavy-handed, and as best I can tell your overwritten version omits some logic that it probably should not (see the core theme_image_style()). This could explain why things "break".

You would probably be better off implementing a preprocessing function that simply alters that 'attributes' variable that your site's exiting image_style theme function uses, something like:

function mytheme_preprocess_image_style(&$vars) {
  if ($vars['style_name'] == 'front_page_recent_blogs' || $vars['style_name'] == 'blog_page_view') {
    $vars['attributes']['class'][] = 'img-responsive';
    // etc... add other var adjustments as needed
  }
}

You may also be able to avoid custom theme changes altogether if you have enough flexibly in your CSS. It sounds like you need to add some CSS rules only to images in specific fields within specific views, so CSS like this may work too:

.view-id-my_view_name .views-field-field-my-field img {
  // Add your CSS for .img-responsive here
} 

Of course this may require duplicating the CSS for .img-responsive if it's used all over the place already (probably likely), which may only be realistic if you are using a CSS preprocessor. I assume you ruled this out already for good reason, but I figured I'd mention it anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.