【问题标题】:How can I use a dynamic key/value on a second level in twig?如何在树枝的第二层使用动态键/值?
【发布时间】:2019-06-25 18:43:03
【问题描述】:

这是我的group 数组:

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 ▶}
]

这是我的column 数组:

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

我知道我的id是1:

$id = "1";

对于列键中的每个值,我想从group 数组中打印出相应的值。

所以结果是:

1
ID
hidden

我尝试用树枝来实现这一点

{% for key, value in column %}
   {% for k, v in group %}
      {{ v.[value] }};
   {% endfor %}
{% endfor %}

错误是:

预期的名称或号码。

注意:这个Symfony2 / Twig - getting array from dynamic array key 对我没有帮助,因为它只解释了如何使用像这样的v[value] 或这个v[key] 的值,而不是像这样的v.[value] 的第二级。

【问题讨论】:

  • 对不起,这个例子对我来说有点不清楚,所以我猜了一半。我认为您正在寻找属性函数{{ attribute(v, value) }}。如果这没有帮助,您始终可以编写一个 Twig 扩展并在 php 中解决问题,方法是在函数内部进行打印,或者仅使用函数将两个对象/数组组合成一个更容易处理的简单键值列表在树枝。如果你能澄清这个例子,例如我没有看到 $column 被使用 - 这是 test 对象在模板部分中的内容吗? - 也许我可以给出更好的答案

标签: arrays symfony dynamic twig key


【解决方案1】:

你需要在你的代码中使用两个for-loops 来实现你想要的,

{% for class in classes %}
    if (optionValue == {{ class.id }}) {
        {% for column in columns %}
        var {{ column }} = '{{ attribute(class, column) }}';
        {% endfor %}        
    }
{% endfor %}

demo

【讨论】:

  • 谢谢!测试了它。我不知道为什么会出错:Impossible to access an attribute ("id") on a string variable ("id").
  • 还有错误:An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class App\Entity\myEntity could not be converted to string").
  • 你通过学说获取的classes了吗?
  • 感谢您的所有帮助,很抱歉我无法正常工作:/
  • 昨天,您评论说您创建了columns 数组,对吗?你做了一些$columns = $classes-refColumns - 我指的是classes,你也需要将它传递给视图。你看过我的demo吗?这不是你想要的输出吗?
猜你喜欢
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 2013-09-25
  • 2023-03-13
  • 2014-09-02
  • 2015-07-05
  • 2022-01-02
相关资源
最近更新 更多