In Drupal 7 this was done with the l() command and setting the html option to true. I have found the Link::fromTextAndUrl() method in Drupal 8 but no mention of something similar to the html option.

[EDIT] I think i was not clear with my original question. This is not for an image field; i was simply asking how to wrap a link around:

<img src="path_to_my_img">

This way should be bulletproof:

use Drupal\Core\Link;
use Drupal\Core\Render\Markup;

$url = $node->get('field_url')->getValue();
$imageUri = $node->get('field_image')->entity->getFileUri();
$image = [
  '#theme' => 'image_style',
  '#style_name' => 'medium',
  '#uri' => $imageUri,
  '#width' => 200,
  '#height' => 100
$rendered = render($image)
$linkMarkup = Markup::create($rendered);
$link = Link::fromTextAndUrl($linkMarkup, $url);
$link = $link->toRenderable();

This worked for me:

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_path'))->toString();

I am not sure if this functionality is preserved in D8

You could either do it in a twig template node--[type-name].html.twig

<a href="{{ content.field_url }}"> {{ content.field_image }} </a>

Or you could do it in a custom module manually

$url = $node->get('field_url')->getValue();
$image_uri = $node->field_image->entity->getFileUri();
$image_url = \Drupal\image\Entity\ImageStyle::load("large")->buildUrl($image_uri);
$image_with_link = "<a href='" . $url . "'>" . $image_url . "</a>";
  • I was looking for the replacement of the l() function; you have just typed out the html for an A tag.
    – liquidcms
    Feb 5 '18 at 21:03

Yes, Link::fromTextAndUrl() is the replacement for l(), but in D8 you use toRenderable() instead of a html option. This produces a render array which is rendered later.

use Drupal\Core\Link;

  $renderable = Link::fromTextAndUrl($title, $url)

BTW you can build this render array directly, with the same result, or the image as title, see Render image that is linked

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.