Jak*_*cey 6 php drupal drupal-8 drupal-modules
我完全知道如何在Drupal 7中这样做,所以我将解释我通常使用Drupal 7做什么.
在制作自定义模块时,我经常使用hook_theme,它非常强大且可重复使用!
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
然后我会使用这个主题
theme('name_of_theme', array(
'param1' => 'VALUEA',
'param2' => 'VALUEB'
));
Run Code Online (Sandbox Code Playgroud)
这将返回html,我会很高兴.
所以Drupal 8需要掌握它.
/**
* Implements hook_theme().
*/
function helloworld_theme() {
$theme = [];
$theme['helloworld'] = [
'variables' => [
'param_1' => [],
'param_2' => 'hello',
]
];
return $theme;
}
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我正在使用
$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
];
Run Code Online (Sandbox Code Playgroud)
我正在获取模板的输出,但是我不确定的是在哪里传递我的参数以便它们在我的模板中可用(只是为了指出我的变量可用它们只是在hook_theme中定义的null)
我也倾向于认为我可能会做出根本性的错误,并且如果我的方法不是最佳实践,我会接受替代路线.
发现问题了,
改变这个,
$hello_world_template = array(
'#theme' => 'helloworld',
'variables' => [
'param_1' => 'hello world',
'param_2' => 'hello from another world'
],
);
Run Code Online (Sandbox Code Playgroud)
对此,
$hello_world_template = array(
'#theme' => 'helloworld',
'#param_1' => $param_1,
'#param_2' => $param_2
);
Run Code Online (Sandbox Code Playgroud)
我现在可以看到我传递的变量。
我仍然愿意寻求更好的选择吗?