将参数从内容类型传递到模块 [英] passing a parameter from a content type to a module
问题描述
我以为这很容易,但是我很沮丧.
I assumed this would be easy but I am stumped.
我有一个包含id字段的自定义内容类型.我用一个基本的页面模板来渲染它们.
I have a custom content type that includes an id field. I render these with a basic page template.
我已经编写了一个小模块,该模块创建了一个块,并在其中填充了来自外部API的数据.一切正常,但我似乎无法弄清楚如何将给定页面内容中的id值传递给模块,以便可以进行API调用.
I have written a small module that creates a block which is populated with data from an external API. Everything works except I cannot seem to figure out how to pass the value of the id from the content of a given page to my module so it can make the API call.
在直接的php中将是几行代码,在Drupal 8和twig中不会那么复杂吗?
It would be a couple of lines of code in straight php, it can't be that complicated in Drupal 8 and twig can it?
推荐答案
I managed to find a solution here
如果有其他用途,我会重新发布它.
I am re-posting it in case it is useful to anyone else.
如果您要生成自定义块,则可以通过块构建函数内部的路由系统访问内容字段,如下所示:
If you are generating a custom block you can access content fields via the routing system inside your block build function like this:
public function build() {
if ($node = \Drupal::routeMatch()->getParameter('node')) {
$field_my_custom_value = $node->field_my_custom_value->value;
}
//do something with the variable, like make the API call
//Make sure to set the cache to the context or even to zero if you need
return array(
'#markup' => $this->t('my content to render'),
'#cache' => array(
'contexts' => ['contexts' => ['route']],
),
);
}
这篇关于将参数从内容类型传递到模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!