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
Comments
Thanks!
Thanks a lot for this useful post! Googled a lot until came across your article!
Post new comment