如何使用多维数组树枝属性?

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

我从数组访问动态数据:

{% for key, value in columns_arr %}
  {% for k,v in group %}
    var {{ value }} = "{{ attribute(v, value) }}";
  {% endfor %}
{% endfor %} 

这样做是为了nameid(见下文)运作良好。在name属性的例子...

{{ attribute(v, value) }}

是更换:

{{ v.name }}

id的例子是取代...

{{ v.id }}

但是,这是不是与type工作,因为在这里我确实需要更换:

{{ v.type.name }}

所以我的问题是,如何将这个样子的属性功能?我试图{{ attribute(v.name, value) }},但我得到的错误

不可能在一个字符串变量(“ID”)访问的属性(“类型”)。

组:

array:4 [▼
  0 => Fields {#7444 ▼
    -id: 1
    -name: "ID"
    -unique_id: "6ab8c870ed"
    -productgroup: PersistentCollection {#7448 ▶}
    -type: Type {#7525 ▼
      +__isInitialized__: true
      -id: 2
      -name: "hidden"
      -unique_id: "5e1086c862"
      -label: "hidden"
       …2
    }
  }
  1 => Fields {#7526 ▶}
  2 => Fields {#7530 ▶}
  3 => Fields {#7534 ▶}
]

columns_arr:

array:3 [▼
  0 => "id"
  1 => "name"
  2 => "type"
]

根据这个问题,我的方法:

How to check a multidimensional Twig array for values?

{% for key, value in columns_arr %}
  {% for k,v in group %}
       {% for k1,v1 in v %}
          var {{ value }} = "{{ attribute(name, v1) }}";
       {% endfor %} 
  {% endfor %}
{% endfor %} 

但是,这给了我一个错误,我的页面没有加载了。

另一种方法是这样的:

{{ attribute(v, [value.name]) }}

但我得到的错误:

不可能在一个字符串变量(“类型”)访问的属性(“名称”)。

arrays symfony attributes twig
1个回答
1
投票

如果你能柱阵列更改为类似2 => 'type.name',你可以用下面的代码片段读出嵌套数据:

{% for value in data %}
    {% for column in columns %}
        {% set output = value %}
        {% for method in column|split('.') if method != '' %}
            {% set output = attribute(output, method) | default('') %}
        {% endfor %}
        {{ output }}
    {% endfor %}
{% endfor %}

demo

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