如何在块状树枝模板中显示当前页面的字段

How can I display the field of the current page in a block twig template

在我的 Basic page 内容类型中,我有一个名为 sidebar_image 的图像字段。

我在名为 header_block 的页眉区域放置了一个块,该区域使用自定义树枝模板。我想知道如何让 Basic page sidebar_image 显示在我的 header_block 树枝模板中:

<h1>Some header</h1>
<img src="{{ sidebar_image }}" />

在预处理函数中:

THEME_preprocess_block__header_block {
  $variables['sidebar_image'] = // get current pages sidebar image URL
}

您应该能够像这样加载当前页面(节点):

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

https://drupal.stackexchange.com/questions/145823/how-do-i-get-the-current-node-id

然后应该可以访问如下字段值:

$node->get('field_sidebar_image')->getValue();

https://drupal.stackexchange.com/questions/144947/how-do-i-access-a-field-value-for-an-entity-e-g-node-object

只需添加一些检查您的节点是否属于特定内容类型和类似内容。