【问题标题】:Accessing the referencing / parent element in twig (paragraphs)访问 twig 中的引用/父元素(段落)
【发布时间】:2019-02-18 03:08:41
【问题描述】:

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

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

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

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

【问题讨论】:

  • 我认为这与 Twig 无关,因为每个模板中的现有变量都是 Drupal 或模块特定的,不是吗?此外,我没有收到“我到目前为止尝试过什么”的问题,因为我只是询问是否有可用的变量(在引用实体的模板中),它包含引用实体字段或其他内容。跨度>
  • paragraph.field_paragraph_reference.getvalue|length 给了我引用元素中的数量 - 但我必须通过它才能在引用的段落中访问它。我发现这个问题有点相关(drupal.stackexchange.com/questions/242601/…),但提供的解决方案无论如何都不起作用,如果我错了,请纠正我。

标签: drupal-modules drupal-8 drupal-theming drupal-templates


【解决方案1】:

在树枝上:

{% set paragraph_parent = paragraph.getParentEntity() %}
{% set width = paragraph_parent.field_width.0.value %}

<div class="{{ width }}">{{ content.field_images }}</div>

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 您可以将此代码添加为 twig 函数或过滤器以在模板中访问它
    • 这个函数是让一个变量可用于特定段落类型的树枝模板。通过{{ mymodule_theming_sources.siblings_total }} 致电。我最初的问题是数据是否已经在 Twig 中可用。
    • 你可以使用$parent_field_name = $paragraph-&gt;get('parent_field_name')-&gt;value;而不是硬编码field_paragraph_reference
    猜你喜欢
    • 2018-06-04
    • 1970-01-01
    • 2016-08-13
    • 2013-01-01
    • 1970-01-01
    • 2021-09-05
    • 2017-01-12
    • 2020-10-05
    • 2018-12-09
    相关资源
    最近更新 更多