Search code examples
drupal-7hookrelative-pathabsolute-path

Drupal 7 theme_image src absolute path from absolute uri


Currently rendering an image using:

$desktop_img = theme('image', array(
      'path' => drupal_get_path('module', 'my_awesome_module') . '/images/desktop.png',
      'width' => 20,
      'height' => 20,
      'alt' => t('View pc version'),
    ));

Which renders as:

<img src="http://myawesome.site/sites/all/modules/custom/my_awesome_module/images/desktop.png" width="20" height="20" alt="View pc version" />

but what I want is:

<img src="/sites/all/modules/custom/my_awesome_module/images/desktop.png" width="20" height="20" alt="View pc version" />

Right now we have a solution to use:

function another_awesome_module_file_url_alter(&$uri) {
  // Get outta here if there's an absolute link
  if (strpos($uri, '://') !== FALSE) {
    return;
  }

  // If the path includes references a gif/jpg/png images elsewhere
  if (strpos($uri, conf_path()) !== FALSE ||
      preg_match('/\.(jpg|gif|png)/i', $uri)) {
    $uri = $GLOBALS['base_path'] . ltrim($uri, '/');
  }
}

to return absolute paths for ALL files. So my question is, is there a drupally way of doing this in theme_image just for the images at hand, instead of altering the path for all files?


Solution

  • Use the base_path() function to get the correct path, then you are giving the theme function an absolute path.

    $desktop_img = theme('image', array(
      'path' => base_path() . drupal_get_path('module', 'my_awesome_module') . 
                '/images/desktop.png',
      'width' => 20,
      'height' => 20,
      'alt' => t('View pc version'),
    ));
    

    The problem is not with drupal_get_path, it gives a relative path, is in the image theme.