Drupal 8将自定义变量传递给主题模板
问题描述:
所以我有一个已经配置了路由的控制器,我的动作看起来像这样
So I have a controller with a route already configured my action looks like this
/**
* 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_filter,但我从未看到过.
I would like to use #brands and #brands_filter in my twig template theme file page--brands, but I never see it go through.
任何人都可以帮忙吗?
谢谢
更新
解决了
在您的模块my_module.module文件中添加以下内容
In you modules my_module.module file add the following
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) : []
]
这将注入变量希望对其他有此问题的人有所帮助,希望文档更好:)
This will inject the variable Hope this helps omeone else who has this problem, wish the docs were better :)
答
请参考以下示例代码:
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
Twig File Name inside templates folder - mypage-template.html.twig