7

When using just drupal_get_path() to include an image from a module directory, this produces non-existent urls when using language prefixes.

I've seen a couple of modules prepend base_path() to deal with this, but on the api page for base_path() someone comments that you should use the DRUPAL_ROOT constant. What is the recommended way?

5 Answers 5

8

Drupal core uses file_create_url() for internal images like this (eg, the default favicon.ico handling in includes/theme.inc).

This ensures that hook_file_url_alter() gets called (the CDN module does this), that the basepath gets set, and that everything is escaped properly.

So, I would use

$path = drupal_get_path('module', 'mymodle');
$url = file_create_url($path . '/images/some.jpg');
2
  • 2
    Worth noting, file_create_url is used by theme_image Jul 13, 2013 at 9:28
  • 1
    Yeah, and @DavidThomas's answer is most appropriate if you want an actual <img> element.
    – mpdonadio
    Jul 16, 2013 at 21:10
4

You could use

theme_image

e.g:

  $variables = array(
    'path' => drupal_get_path('module', 'my_module').'/images/image.jpg', 
    'alt' => 'My image',
    'title' => 'My image title',
    'attributes' => array('class' => array('my-image')),
  );
  $img = theme('image', $variables);
0
1

You should use $base_url with drupal_get_path().

global $base_url;
$img_path = $base_url . '/' . drupal_get_path('module', 'YOUR_MODULE') . '/images/your_image.png';

In this way the image path won't be affected by i18n site url prefix settings.

0

Use the System stream wrapper module. It gives you a module://, theme:// and profile:// stream wrapper. These wrappers will (probably) be part of D8 core.

0

Sometime you may need to pass a NULL langage in the url function.

Example from commerce_paypal

Not working link (original code)

  return url(drupal_get_path('module', 'commerce_paypal_ec') . '/images/paypal-ec-logo.gif', array('absolute' => TRUE));

Working link (hacked code)

  return url(drupal_get_path('module', 'commerce_paypal_ec') . '/images/paypal-ec-logo.gif', array('absolute' => TRUE, 'language' => ""  ));

Note: Hacking contributed modules is never reccomanded, of course.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.