Drupal 8将自定义变量传递给主题模板

Mat*_*mas 9 drupal-8

所以我有一个已配置路由的控制器我的动作如下所示

/**
 * List of brands
 *
 * @return array
 */
public function listAction()
{
    $brandIds = \Drupal::entityQuery('node')
        ->condition('type', 'brand')
        ->sort('title', 'asc')
        ->execute();

    return [
        'addition_arguments' => [
            '#theme' => 'page--brands',
            '#brands' => is_array($brandIds) ? Node::loadMultiple($brandIds) : [],
            '#brands_filter' => \Drupal::config('field.storage.node.field_brand_categories')->get()
        ]
    ];
}
Run Code Online (Sandbox Code Playgroud)

我想在我的树枝模板主题文件页面中使用#brands和#brands_filter - 品牌,但我从未看到它经历过.

有人可以帮忙吗?

谢谢

UPDATE

解决了这个问题

在您的模块my_module.module文件中添加以下内容

function module_theme($existing, $type, $theme, $path)
{
    return [
        'module.brands' => [
            'template' => 'module/brands',
            'variables' => ['brands' => []],
        ],
    ];
}
Run Code Online (Sandbox Code Playgroud)

在您的控制器中使用

return [
        '#theme' => 'mymodule.bands',
        '#brands' =>is_array($brandIds) ? Node::loadMultiple($brandIds) : []
]
Run Code Online (Sandbox Code Playgroud)

这将注入变量希望这有助于omeone有这个问题的其他人,希望文档更好:)

小智 1

请参考下面的示例代码:

mymodule.module

<?php

/**
 * @file
 * Twig template for render content
 */

function my_module_theme($existing, $type, $theme, $path) {
  return [
    'mypage_template' => [
      'variables' => ['brands' => NULL, 'brands_filter' => NULL],
    ],
  ];
}
?>
Run Code Online (Sandbox Code Playgroud)

mycontorller.php

<?php
/**
 * @file 
 * This file use for access menu items  
 */
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class pagecontroller extends ControllerBase {
        public function getContent() {
      return [
        '#theme' => 'mypage_template',        
        '#brands' => 'sampleBrand', 
        '#brands_filter' => 'sampleBrands_filter',       
      ];
  }
}
Run Code Online (Sandbox Code Playgroud)

模板文件夹内的 Twig 文件名- mypage-template.html.twig