我想在Drupal 8的Twig文件中使用一个变量。并且该树枝变量应该可用于网站的所有页面。
假设我在窗体或控制器中创建了一个变量$my_variable
。 所以现在我想在我的 twig 文件中使用此$my_variable
。
Like this {{ my_variable }}.
我已经尝试过这种方法:
获取 $tempstore 在 twig 文件中 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>
任何帮助将不胜感激。 谢谢!
一个完整的测试模块,其中包含在 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}}
在mymodulename/templates/my-template-name.html.twig
中创建树枝文件
<div>{{ my_variable }}</div>
然后在mymodulename.module
中添加hook_theme
:
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];