如何向 Drupal 8 中的现有模板配置添加其他变量?

How to add additional variables to an existing template config in Drupal 8?

我在一个模块中有一个主题配置。

/**
* Implements hook_theme().
*/
function module1_context_theme($existing, $type, $theme, $path) {
 return [
  'custom_theme' => [
    'template' => 'custom_theme',
    'variables' => [
      'var1' => NULL,
      'var2' => NULL,
    ],
   ],
 ];
}

我想通过其他模块向主题配置添加一个额外的变量。 我该怎么做?

您可以使用 HOOK_theme_registry_alter 来改变它。试试下面的代码。

/**
* Implements hook_theme_registry_alter
*/
function my_module_theme_registry_alter(&$theme_registry) {
  $theme_registry['custom_theme']['variables'][] = 'var3';
}