User login

Wrapping a link around a renderable array for images in Drupal 7

I was asked a question about theming linked images and gave the wrong answer, that it was a known pain point, but it kept bugging me because i was pretty sure i was not remembering something. The failure of link render arrays i was thinking of is their use in item_list, but in fact there is a secret theme function that can be used to put linked images in a render array properly.

Thanks to the amazing Morbus Iff for documenting using theme_image_formatter in a render array:

<?php
    $build
['image'] = array(
     
'#theme' => 'image_formatter',
     
'#item' => array(
       
'uri' => 'misc/druplicon.png',
      ),
     
'#path' => array(
       
'path' => 'node',
       
'options' => array('html' => TRUE),
      ),
    );
?>

Alt and title text would go in #item as alt and title.

Here is an example from Drupal core's image field module, where the image render array is passed in as $item:

<?php
 
foreach ($items as $delta => $item) {
    if (isset(
$link_file)) {
     
$uri = array(
       
'path' => file_create_url($item['uri']),
       
'options' => array(),
      );
    }
   
$element[$delta] = array(
     
'#theme' => 'image_formatter',
     
'#item' => $item,
     
'#image_style' => $display['settings']['image_style'],
     
'#path' => isset($uri) ? $uri : '',
    );
  }
?>

One ought to be able to pass a renderable array into a renderable array that is a link type or set to #theme => link.

But you cannot.

Being worked on:
Arguments to theme as renderable array in a render array. Allow better nesting of html element.
http://drupal.org/node/1295958

Geek question - Why is there no render array for links in D7?
http://groups.drupal.org/node/145064

http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_link/7

For images there is another theme function that works:
http://www.disobey.com/node/1894

Searched words: 
theme_link for image drupal 7 theme_link take render array site:drupal.org drupal 7 wrap content in link render array

Comments

Thanks!

Thanks a lot for this useful post! Googled a lot until came across your article!

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.