Meules
Meules

Reputation: 1389

Twig merge multiple things in an array

I'm trying to create an array with dates in it for an order system. Those dates corresponds with days that the shop can't deliver.

I'm having trouble to create that array since values are strings and that keeps getting producing an error with the merge filter. I have only access to the frontend of the shop so I can't create custom functions whatsover.

The end result need to be an array with all dates in it so I can use that as javascript array, like so:

var closed = [
  {{ closedDates }} // ["01-01-2018", "02-01-2018", etc...]      
];

So what I have is this:

1) Webshop fills in the single days they are closed and perhaps a range of days. That are three variables like:

 {{ closedDays }} {# produces eg 01-01-2018, 02-01-2018, 03-01-2018 { it's dd-mm-yy #} 
 {{ date_range_start }} {# produces eg. 10-01-2018 #}
 {{ date_range_end }} {# produces eg. 20-01-2018 #}

2) So what I did is this:

 {% set closedDates = [] %}    


  {% if theme.closedDays %}
    {% set foo = theme.closedDays %}
    {% for i in foo | slice(0, 5) %}
       {% set closedDates = closedDates | merge(i) %}
    {% endfor %}

  {% endif %}

  {% if theme.date_range_start and theme.date_range_end  %}
     {% set start_date = theme.date_range_start  %}
     {% set end_date = theme.date_range_end %}

     {# below function lists all days between start and end date #}
     {% for weekRange in range(start_date|date('U'), end_date|date('U'), 86400 ) %}
        {% set closedDates = closedDates | merge(weekRange | date('d-m-Y')) %} 
     {% endfor %}
  {% endif %}

When I do it like above I get an error saying The merge filter only works with arrays or hashes;. But how do you create an array then with those values? That's only done with merge right?!

Any help greatly appreciated.

Upvotes: 5

Views: 25908

Answers (1)

entio
entio

Reputation: 4273

In Twig you can't just push elements to an array. Instead, you have to merge array with another array.

Given one array:

{% set firstArray = ['a', 'b'] %}

if you want to add element 'c', you have to merge it providing an array, even if you want to add single string element.

{% set firstArray = firstArray | merge(['c']) %}

If you work with associative arrays, it's analogical:

{% set secondArray = {'a': 'string a', 'b': 'string b' } %}
{% set secondArray = secondArray | merge({'b': 'overwritten!', 'c': 'string c' }) %}

The only diference is that element b will be overwritten with the value from the secondArray, so you'll get:

{
   'a': 'string a',
   'b': 'overwritten!',
   'c': 'string c'
}

Upvotes: 14

Related Questions