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



我在(父(段落中有一个实体引用字段,该字段引用多个子段落。

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

实际上,我只是在尝试计算引用项的树枝模板本身中的一个引用项总数。所以如果你想的话,我想数它的兄弟姐妹 + 1。

我知道我可以在模块中预处理它,但我想知道这在 twig 中是否可行。

在树枝中:

{% set paragraph_parent = paragraph.getParentEntity() %}
{% set width = paragraph_parent.field_width.0.value %}
<div class="{{ width }}">{{ content.field_images }}</div>

另一种使用带有 2 条简单线条的树枝的方法。它工作正常。

{% set parent = paragraph._referringItem.parent.parent.entity %}
{{ parent.title.value }}

由于这个问题没有回应,我不得不假设这在 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;
}

最新更新