2

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"
  }
%}
0

2 Answers 2

4

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 
#}
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! However I changed the struct to a simple dictionary to avoid the overhead. thanks damien
Can the downvoter explain his -1? This is a clean solution, and perfectly valid in Twig
1

I have some very dirty, but working solution:

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

3 Comments

what a dirty trick, it works but damien has a better solution! :)
Yeah, I'm ashamed I've posted something like this... :<
ahaha, just don't: sometimes quircks are needed to get to the end of the day. fortunately my brain got back working again and came out with a better solution too :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.