首页 > 解决方案 > Drupal 7 theme_image src 来自绝对 uri 的绝对路径

问题描述

当前使用以下方式渲染图像:

$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'),
    ));

呈现为:

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

但我想要的是:

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

现在我们有一个解决方案可以使用:

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, '/');
  }
}

返回所有文件的绝对路径。所以我的问题是,是否有一种在 theme_image 中仅针对手头的图像执行此操作的方式,而不是更改所有文件的路径?

标签: drupal-7hookrelative-pathabsolute-path

解决方案


使用base_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'),
));

问题不在于drupal_get_path,它给出了相对路径,在图像主题中。


推荐阅读