我想在Drupal 8的Twig文件中使用一个变量,并且该twig变量应该可用于网站的所有页面。
假设我在窗体或控制器中创建了一个变量$my_variable
。所以现在我想在我的树枝文件中使用此$my_variable
。
Like this {{ my_variable }}.
我已经尝试过这种方法:
get $tempstore inside a twig file drupal 8
我的模块文件:
function my_module_theme() {
return [
'theme_tag' => [
'variables' => ['my_variable' => NULL],
],
];
}
我的控制器:
public function callMe() {
$my_variable= "some data here";
return [
'#theme' => 'theme_tag',
'#my_variable' => $my_variable,
];
}
我的树枝:
<p> {{ my_variable}} </p>
任何帮助将不胜感激。 谢谢!
答案 0 :(得分:2)
带有在git hub上创建的模板的完整测试模块,您也可以进行检查。 https://github.com/nassernak/drupal8-custom-template
您需要定义树枝模板的路径
'path' => $path . '/templates',
'template' => 'twig-template-file-name',
$path
->引用您的模块目录
templates
->是包含您的模板的文件夹
template
->仅文件名不带扩展名,在我的情况下不带扩展名.html.twig
。
完全像这样定义主题钩子,然后在变量数组中设置变量。
function your_module_name_theme($existing, $type, $theme, $path) {
return [
'theme_tag' => [
'variables' => [
'var2' => NULL,
'var2' => NULL,
],
'path' => $path . '/templates',
'template' => 'twig-template-file-name-without-extention',
],
];
}
然后在回调函数中引用模板的示例。
public function basePageCallback() {
return [
'#theme' => 'theme_tag',
'#var1' => 'test',
'#var2' => 'test2',
];
然后在树枝上访问它
{{var1}}
答案 1 :(得分:0)
在mymodulename/templates/my-template-name.html.twig
<div>{{ my_variable }}</div>
然后在hook_theme
中添加mymodulename.module
:
function mymodulename_theme($existing, $type, $theme, $path) {
return [
'my_template_name' => [
'variables' => [
'my_variable' => 'default value',
],
],
];
}
通话模板:
// Call the mail template
$template = [
'#theme' => 'my_template_name',
'#my_variable' => 'my variable value',
];
// Render the template
$rendered_template = \Drupal::service('renderer')->render($template);
return ['#markup' => $rendered_template];