如何获取当前Drupal主题的路径?

29

Drupal API 提供了 drupal_get_path($type, $name) 函数,用于获取特定主题或模块的路径。如果我想获取当前主题的路径怎么办?


使用当前主题路径时要小心。如果有人从您的主题创建子主题,则当前主题路径将是子主题的路径,而不是您的路径!这可能会破坏您自己的主题或子主题。- 至少在D8中。 - golddragon007
9个回答

27

3
请注意,当从“theme_*”函数内部调用path_to_there时,它将返回当前模块的路径而不是当前活动主题的路径,这可能会导致错误,请参考此错误报告中的更多详细信息:http://drupal.org/node/194098。 - webdevbyjoss

20

这应该可以正常工作 (文档):

global $theme;
$path = drupal_get_path('theme', $theme);

// there's also a $theme_path global

global $theme_path;

最好使用path_to_theme(),而不是使用$theme_path - apaderno
2
为什么使用path_to_theme()比$theme_path更好? - timoxley
@timoxley,唯一的区别是如果$theme_path未设置,则会初始化主题,然后返回新的$theme_path。请参见path_to_theme - htoip
我注意到在字段模板中使用的path_to_theme()和$theme_path会给我提供到模块field/module的路径。唯一正确显示的是$theme。 - Kandinski

10
在D6中,根据使用方式的不同,path_to_theme()可能无法按照您的预期工作。如果您在任何主题预处理函数之外使用它,那么它可能会给您想要的结果,但是如果它在模块的主题/预处理钩子函数的上下文中被调用...它将指向声明主题的模块路径。
例如,如果我有一个名为“my_theme”的主题和一个名为“my_module”的模块,该模块使用预处理钩子覆盖论坛主题,那么在我的模块中调用path_to_theme():例如my_module_preprocess_forums()...将返回“forums”,而不是人们可能期望的“my_theme”。
如果你问我,这非常奇怪。

9
在Drupal 8中,如果您需要在管理主题激活时获取活动主题路径,可以获取默认主题路径:
$themeHandler = \Drupal::service('theme_handler');
$themePath = $themeHandler->getTheme($themeHandler->getDefault())->getPath();

3
我认为 Drupal 8/9 的最佳答案是... - Renrhaf

5
在Drupal 7中,获取当前主题路径的方法是使用path_to_theme()函数。

4
在Drupal 8中,
global $base_url;
$theme = \Drupal::theme()->getActiveTheme();
$image_url = $base_url.'/'. $theme->getPath() .'/images/image.jpg';

这不是最好的方式 - 请参考其他答案。 - Adaddinsane

1
如果您已经知道主题名称
$themePath = \Drupal::service('extension.list.theme')->getPath('my_theme_name');

或者

 $themePath = \Drupal::service('extension.path.resolver')->getPath('theme', 'my_theme_name');

1

在Drupal 5中,您可以简单地使用:path_to_theme()

这将为您提供从Drupal根目录到特定主题目录的完整路径。请注意,它不包括尾随斜杠。

在Drupal 6中,它的行为略有不同。如果您在页面内调用它,它将调用当前正在进行主题设置的任何内容...无论是您的主题、模块等等。以下是API文档中的关键引用:

它可以指向活动主题或处理主题实现的模块。例如,在主题调用范围内调用时,它将取决于主题函数的处理位置。如果从模块中实现,则会指向该模块。如果从活动主题中实现,则会指向活动主题。当在主题调用范围之外调用时,它将始终指向活动主题。

来源:http://api.drupal.org/api/function/path_to_theme


0

对于D8,主题文件夹在预处理函数中是可用的:

function hook_preprocess_page(&$variables) {
  $variables['some_logo_file'] = "/{$variables['theme']['path']}/images/logo.png";
}

page.html.twig:

<img src="{{ logo_src }}">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接