0

I am currently trying to write a preprocess to change the img tag on 2 views but with no success using the below code:

use Drupal\node\Entity\Node;
function mytheme_preprocess_image(&$variables) {
  $current_route_name = \Drupal::service('current_route_match')->getRouteName();
  $office ='office_view';
  $team  ='team_view';

  if ($current_route_name == "office_view.page_1"){
    $view = Views::getView($office);
  } 
  else if ($current_route_name =="team_view.page_1"){
    $view = Views::getView($team);
  }

  $view->execute();

  foreach ($view->result as $row) {
    $node = $row->_entity;
    $node = Node::load($row->_entity->id());
    $variables['attributes']['class'][] = 'lazy';
    $variables['attributes']['data-src'] =  $variables['attributes']['src'];
    $variables['attributes']['src'] = false;
  }
  return $response;
}

It works up to the point that it matches the route and if I do not use the foreach this code works and changes the img tag structure but it affects other blocks on the view page too.

I only need to / have to change tags in the view.

$variables['attributes']['class'][] = 'lazy';
$variables['attributes']['data-src'] = $variables['attributes']['src'];
$variables['attributes']['src'] = false;

Desired result - all img in those 2 views, have the lazy class, no src but instead a data-src.

  • 1
    I think you should use mytheme_preprocess_views_view instead of mytheme_preprocess_image – berramou Sep 10 at 11:04

Your Answer

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

Browse other questions tagged or ask your own question.