簡體   English   中英

自定義模塊 Drupal 的 Twig 模板中的訪問變量 8

[英]Access variable in Twig template of custom module Drupal 8

我想在 Drupal 8 的 Twig 文件中使用一個變量。並且該 twig 變量應該可用於該站點的所有頁面。

假設我在我的表單或 Controller 中創建了一個變量$my_variable my_variable。 所以現在我想在我的 twig 文件中使用這個$my_variable

Like this {{ my_variable }}. 

我已經嘗試過這種方法:

在 twig 文件 drupal 8 中獲取 $tempstore

我的模塊文件:

function my_module_theme() {
    return [
        'theme_tag' => [
        'variables' => ['my_variable' => NULL],
        ],
    ];
}

我的 Controller:

public function callMe() {
     $my_variable= "some data here";
     return [
          '#theme' => 'theme_tag',
          '#my_variable' => $my_variable,
     ];
}

我的 Twig:

<p> {{ my_variable}} </p>

任何幫助,將不勝感激。 謝謝!

在 git 集線器上創建的帶有模板的完整測試模塊,您也可以檢查它。https://github.com/nassernak/drupal8-custom-template

您需要定義 twig 模板的路徑

'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',
        ],
      ];
    }

然后在您的回調 function 中引用您的模板,使用此示例。

public function basePageCallback() {
    return [
      '#theme' => 'theme_tag',
      '#var1' => 'test',
      '#var2' => 'test2',
    ];

然后在您的 twig {{var1}}上訪問它

mymodulename/templates/my-template-name.html.twig中創建 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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM