0

I'm having issues when trying to get the image URL of an image field, which allows multiple values.

I have a view which has context to a node.

I have two templates, one for the row level of the view, and one for the field level of the view:

views-view--my-view.html.twig:

{% if rows %}
  {{ rows }}
{% endif %}

views-view-fields--my-view.html.twig:

{{ kint(get_image_path(row._entity.field_header_images)) }}

get_image_path():

public function get_image_path(\Twig_Environment $env, array $context, $image, $style=false) {
  // Check if $image is present
  if(is_null($image)) {
    return false;
  }

  kint($image);

  // Object structure different, depending on if node.field_name, content.field_name or row._entity.field_name is passed
  if(isset($image['#items'])) {
    $image = $image['#items'];
  }
  elseif(isset($image['#item'])) {
    $image = $image['#item'];
  }

  // Check $image->entity is set
  if(!isset($image->entity)) {
    return false;
  }

  if(!$style) {
    return $image->entity->url();
  }
  else {
    $image_style = ImageStyle::load($style);
    return $image_style->buildUrl($image->entity->getFileUri());
  }
}

get_image_path() is a function provided by the starter module. It allows you to easily pull out URLs for images (with size support), without having to do the horrible relationship file URI business.

I can't use get_image_path() on fields.field_header_images.content due to its structure, so I have to access the row.

Now what happens is only the first image is returned. So if I had 3 different images, I'd get the URL for the first image 3 times.

If I just use fields.field_header_images.content, I am able to see the 3 different images without issue.

Hopefully I'm not being too unclear/broad!

Thanks in advance.

  • I have limited experience with 8 so far, but on 7, I was able to pull the image path through Views UI. You'd have to rewrite the output of the field, and use the appropriate replacement tokens. I'm not sure if that's what you're looking for though. – Kellen Mar 30 '17 at 16:12
0

I'm the author of the Starter module you reference. I've made a change to the get_image_path() twig extension, in order to support images in passed by these means.

In order for this to work as required, you need to change your view - under Multiple Field Settings for your field, tick 'Display all values in the same row'. This will ensure that the fields aren't output as a multiple of the total number.

Then, in your view fields template, use:

{% for item in row._entity.field_header_images %}
  {{ get_image_path(item.getValue()) }}
{% endfor %}

Hope this helps.

|improve this answer|||||

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.