Twig:循环遍历一系列对象

时间:2014-06-10 14:02:34

标签: php twig

我想知道是否有任何方法可以使用Twig循环到这样的结构:

{%
  set languages = [
    {"english": "en"},
    {"spanish": "es"},
    {"italian": "it"},
    {"german": "de"},
    {"french": "fr"},
    {"portuguese": "pt"},
  ]
%}

{% for value in languages %}
  Language: {{value.??}} - Locale: {{value.??}}
{% endfor %}

我不喜欢将对象拆分为“键值”对,只是为了拥有名为...的任何方法来实现这个目标?

同时我按如下方式修改了结构,以使用简单的键值循环:

{%
  set languages = {
    "english": "en",
    "spanish": "es",
    "italian": "it",
    "german": "de",
    "french": "fr",
    "portuguese": "pt"
  }
%}

2 个答案:

答案 0 :(得分:4)

您也可以使用相同的键/值对遍历对象:

{%
  set languages = [
    {"english": "en"},
    {"spanish": "es"},
    {"italian": "it"},
    {"german": "de"},
    {"french": "fr"},
    {"portuguese": "pt"},
  ]
%}

{% for value in languages %}
  {% for k, v in value %}
    Language: {{k}} - Locale: {{v}} <br />
  {% endfor %}
{% endfor %}

{# output:
  Language: english - Locale: en
  Language: spanish - Locale: es
  Language: italian - Locale: it
  Language: german - Locale: de
  Language: french - Locale: fr
  Language: portuguese - Locale: pt 
#}

答案 1 :(得分:1)

我有一些非常肮脏但有效的解决方案:

{% for value in languages|keys %}
    Language: {{ languages[value]|keys|first }} - Locale: {{ languages[value]|first }}
{% endfor %}