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

2024-02-05

所以我有一个控制器,其路线已配置,我的操作如下所示

/**
 * 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()
        ]
    ];
}

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

有人可以帮忙吗?

谢谢

UPDATE

解决了

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

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

在您的控制器中使用

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

这将注入变量希望这可以帮助其他遇到此问题的人,希望文档更好:)


请参考下面的示例代码:

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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Drupal 8 将自定义变量传递到主题模板 的相关文章

随机推荐