gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:10:27 26 4
gpt4 key购买 nike

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

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

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

有人可以帮忙吗?

谢谢

更新

解决了

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

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

在您的 Controller 中使用

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

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

最佳答案

请引用下面的示例代码:

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

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

关于drupal-8 - Drupal 8 将自定义变量传递到主题模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39120390/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com