dongou6632 2014-06-10 14:02
浏览 383
已采纳

Twig:循环遍历一系列对象

I was wondering if is there any way to loop to such a struct with Twig:

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

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

I don't like to split object in a "key value" pair just to have properties named... any way to achieve this?

In the meanwhile I modified the struct as follows to use a simple key value looping:

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

2条回答 默认 最新

  • doru52911 2014-06-10 14:12
    关注

    You can loop over the object too, using the same key/value pair:

    {%
      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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?