Sachin I
Sachin I

Reputation: 1508

Merge key and value into an array in Twig file

I want to add key and value into array in twig file. But I am facing following issue "Twig_Error_Syntax: A hash key must be a quoted string or a number"

{% set phoneCount = 0 %}
{% set phoneNumbers = {} %}
{% for currPhone in currBroker.phones %}
    {% if (currPhone.type == 'Work' or currPhone.type == 'Mobile') and phoneCount <= 2 and currPhone.number !='' %}
        {% set phoneCount = phoneCount + 1 %}                   
        {% set phoneNumbers = phoneNumbers|merge({ currPhone.type:currPhone.type }) %}
    {% endif %}
{% endfor %}
{{ phoneNumbers|print_r }}

I just need the syntax of merging key and value into array. I tried by giving static inputs and its works

{% set phoneNumbers = phoneNumbers|merge({ 'work':'(011)112-1233' }) %}

But its not working for dynmic input. Please help!!

Upvotes: 3

Views: 12300

Answers (1)

Rapha&#235;l Mali&#233;
Rapha&#235;l Mali&#233;

Reputation: 4012

You have to wrap your key in braces :

{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}

Tested and working example :

{% set currPhone = {type: 'test'} %}
{% set phoneNumbers = {} %}
{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}
{% dump(phoneNumbers) %}

I get :

array:1 [▼
  "test" => "test"
]

Upvotes: 10

Related Questions