在自定义模块 Drupal 8 的 Twig 模板中访问变量

Access variable in Twig template of custom module Drupal 8

我想在 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>

如有任何帮助,我们将不胜感激。 谢谢!

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];

A complete test module with template created on git hub you can check that as well. 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}}