Php 在模块内使用hook_主题将变量传递给twig
我完全知道如何在Drupal7中做到这一点,所以我将解释我通常使用Drupal7做什么 在制作自定义模块时,我经常使用hook_主题,它非常强大且可重用Php 在模块内使用hook_主题将变量传递给twig,php,drupal,drupal-modules,drupal-8,Php,Drupal,Drupal Modules,Drupal 8,我完全知道如何在Drupal7中做到这一点,所以我将解释我通常使用Drupal7做什么 在制作自定义模块时,我经常使用hook_主题,它非常强大且可重用 /** * Implements hook_theme(). */ function MODULE_theme() { $themes = array(); $themes['name_of_theme'] = array( 'path' => drupal_get_path('module', 'mod
/**
* Implements hook_theme().
*/
function MODULE_theme() {
$themes = array();
$themes['name_of_theme'] = array(
'path' => drupal_get_path('module', 'module') .'/templates',
'template' => 'NAME_OF_TEPLATE',
'variables' => array(
'param1' => NULL,
'param2' => NULL,
),
);
return $themes;
}
然后,我将使用
theme('name_of_theme', array(
'param1' => 'VALUEA',
'param2' => 'VALUEB'
));
这将返回html,我会很高兴
所以Drupal8已经过时了,我们需要抓住它
/**
* Implements hook_theme().
*/
function helloworld_theme() {
$theme = [];
$theme['helloworld'] = [
'variables' => [
'param_1' => [],
'param_2' => 'hello',
]
];
return $theme;
}
在我的控制器中,我正在使用
$hello_world_template = array(
'#theme' => 'helloworld',
'variables' => [
'param_1' => 'hello world',
'param_2' => 'hello from another world'
],
);
$output = drupal_render($hello_world_template,
array(
'variables' => array(
'param_1' => $param_1,
'param_2' => $param_2,
)
)
);
return [
'#type' => 'markup',
'#markup' => $output
];
我得到了一个模板的输出,但是我不确定的是在哪里传递我的参数,以便它们在我的模板中可用(只是要指出,我的变量是可用的,它们只是在hook_主题中定义的null)
我也愿意接受这样的想法,即我可能做了根本错误的事情,如果我的方法不是最佳实践,我愿意接受另一种途径。发现了问题
改变这个,
$hello_world_template = array(
'#theme' => 'helloworld',
'variables' => [
'param_1' => 'hello world',
'param_2' => 'hello from another world'
],
);
对此,
$hello_world_template = array(
'#theme' => 'helloworld',
'#param_1' => $param_1,
'#param_2' => $param_2
);
我现在可以看到我传递的变量了
我仍然希望有更好的选择?建议不要调用drupal渲染方法。保持它作为一个渲染数组添加尽可能多的内容,最好让drupal在需要时渲染它。Hi@Eyal制作模块页面的最佳实践是什么?创建一个控制器,然后在其中返回一个数组?我不确定该如何渲染这个数组。我不知道我是否讲得通,但在创建模块页面时,我们将其重新调整为主题的内容。除非是块,否则您的注释更有意义。最佳做法是使用控制器并返回渲染数组。渲染数组将放置在主内容块内。如果需要使用hook\u node\u view()对添加到节点的新内容进行主题化,我们如何做?顺便说一句。您应该使用
\Drupal::service('renderer')->renderRoot()
而不是不推荐的Drupal\u render()
。