【问题标题】:Accessing deep values from array从数组访问深层值
【发布时间】:2022-01-06 20:03:46
【问题描述】:

我有一个基本模板节点--some-name.html.twig,我试图从内容变量的子节点访问特定值。

{% for item in content %}
  {{ kint(item) }}
{% endfor %}

这样打印一个期望值(为简洁起见):

Array
(
    [#title] => Body
    [#language] => en
    [#field_name] => body
    [#field_type] => text_with_summary
    [#field_translatable] => 1
    [#entity_type] => node
    [#object] => stdClass Object
        (
            [__CLASS__] => Drupal\node\Entity\Node
            [in_preview] => 
            [values:protected] => Array
                (
                    [body] => Array
                        (
                            [x-default] => Array
                                (
                                    [0] => Array
                                        (
                                            [value] => Body sample goes here
                                            [summary] => summary sample here
                                            [format] => rich_text
                                        )

                                )

                        )
                )
        )
)

但是如果我尝试在我的循环中打印它们,它只会返回 null...我错过了一些超级基本的东西吗?

{% for item in content %}
  {{ item["#object"].values.body[0].value }}
  {{ item["#object"]["values"]["body"][0].value }}
{% endfor %}

打印{{item}} 会按预期提供整个项目,但无论属性或我如何访问它,尝试访问item 的特定更深属性似乎都是空的。

任何帮助将不胜感激。

【问题讨论】:

    标签: drupal twig drupal-modules drupal-themes


    【解决方案1】:

    您的类中的属性values 受到保护,这意味着twig 将无法访问此属性,除非:

    • 您将财产设为values public
    • 您在班级中创建了一个公共 getter getValues

    documentation中所见

    【讨论】:

      猜你喜欢
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2016-07-13
      • 2011-06-22
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多