访问树枝中的引用/父元素(段落)

问题描述 投票:0回答:1

我在(parent-)段落中有一个实体引用字段,它引用了多个子段落。

是否可以在子项(引用段落)的枝条模板中访问引用段落的字段值?

实际上,我只是想计算引用项目的枝条模板本身中的总引用项目。所以如果你愿意的话,我想把它的兄弟姐妹算上+1。

我知道我可以在一个模块中预处理这个事实,但我想知道这是否可能在树枝上。

drupal-modules drupal-8 drupal-theming drupal-templates
1个回答
0
投票

由于对此问题没有回应,我不得不假设这在Twig中是不可能的,但是想通过模块快速分享所提到的解决方法......

getParentEntity()

是你的朋友。

使引用元素的计数可用的简短示例...

/* implements hook_preprocess_paragraph() (paragraph type product_teaser) */
function mymodule_preprocess_paragraph__product_teaser(&$variables) {

  /* makes paragraph siblings count (+ 1/self) available to template */
  $siblings_total = 1;      

  $paragraph = $variables['paragraph'];
  $parent_paragraph = $paragraph->getParentEntity();  

  if ( ( isset($parent_paragraph) ) && ( $parent_paragraph->hasField('field_paragraph_reference') ) ) {

    $field_content = $parent_paragraph->get('field_paragraph_reference')->getValue();

    if ( isset($field_content[0]['target_id']) ) {
      $siblings_total = count($field_content);
    }

  }

  $variables['mymodule_theming_sources']['siblings_total'] = $siblings_total;

}
© www.soinside.com 2019 - 2024. All rights reserved.