3

I am loading an unmananged image file and would like to render it in a block, but it should be linked. I have an uri (public://...) and I am able to render the image using

$build['my_image'] = [ '#theme' => 'image_style', '#style_name' => 'large', '#uri' => $uri, ];

This works, but how can I render it beeing linked to some url?

6

image_formatter is to render an entity field, you can't use that without having that.

Try using a render array for the link, like this:

$type_link_nested_array = [
  '#type' => 'link',
  '#title' => ['#theme' => 'image_style', '#style_name' => 'large', '#uri' => $uri, ],
  '#url' => Url::fromUri('https://www.drupal.org'),
];
2

Without adding image styling (as original question never mentioned that), I found this to work:

use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Core\Render\Markup;
$img = '<img src="path_to_my_image" />';
$rendered_image = render($img);
$image_markup = Markup::create($rendered_image);
$link = Link::fromTextAndUrl($image_markup, Url::fromUri('internal:/my_link_path'))->toString();
1

You'd probably need to render the image yourself and then add the link around it. So something like:

$img_render_array =  [ '#theme' => 'image_style', '#style_name' => 'large', '#uri' => $uri, ];
$img = render($img_render_array)->__toString();
$build['my_image']['#markup'] = '<a href="/">'.$img.'</a>';
  • isn't there any possibilty using '#theme' => 'image_formatter' ? I don't know how to use it. The documentation says: Available variables: * - image: A collection of image data. * - image_style: An optional image style. * - url: An optional URL the image can be linked to. However I don't understand what to pass as image. – tobias554 Feb 2 '18 at 16:39
  • Yes that would work by the looks of it. So in the test code it has: $base_element = array( '#theme' => 'image_formatter', '#image_style' => 'test', '#item' => $entity->image_test, '#url' => Url::fromUri('base:' . $path), ); With $entity->image_test being the image object from a field by the looks of it api.drupal.org/api/drupal/… – Leigh Feb 2 '18 at 17:02
  • I don't have an entity and I don't want to use managed files. What do I need to pass as image/item ? I only have the uri to the image. – tobias554 Feb 2 '18 at 17:10

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.