Working in Twig, I had to add classes to a pre-existing array. Whilst I've grown used to the patterns in PHP, these cannot be applied in Twig. Instead I had to merge the new array elements.
Non associative arrays
Working from a base level, I'll begin as if the original array hasn't been set. The merge filter expects as first argument an array whose content will be merged with the assigned variable:
{% set myArray = [] %}
{% set myArray = myArray|merge(['tw-flex-inline']) %}
{% set myArray = myArray|merge(['tw-rounded-xl', 'tw-border-gray-300']) %}
{#
The content of myArray is
myArray = ['tw-flex-inline','tw-rounded-xl','tw-border-gray-300']
#}Note that you can build any complex content using the same syntax:
{% set myArray = [] %}{% set myArray = myArray|merge([
['tw-flex-inline'],
['tw-rounded-xl', 'tw-border-gray-300'],
['tw-text-gray-600']
]) %}
{% set myArray = myArray|merge([
[
['tw-rounded-xl', 'tw-border-gray-300']
],
[
['tw-text-gray-600']
],
]) %}
Associative arrays
To add items to an associative array, you would only pass as first argument an array with brackets with the new values:
{# Note that the original array in this case has an item #}
{% set myArray = {
"first": 'tw-flex-inline'
} %}
{% set myArray = myArray|merge({
"second": 'tw-rounded-xl'
}) %}
{% set myArray = myArray|merge({
"third": 'tw-border-gray-300'
}) %}
{#
The content of myArray is
myArray = {
"first":'tw-flex-inline',
"second":'tw-rounded-xl',
"third":'tw-border-gray-300'
}
#}Note: that the merge filter uses array_merge in the background, which means that if you are working with an associate array, if the key already exists on the element it will be overwritten:
{# Note that the original array in this case has an item #}
{% set myArray = {
"first": 'tw-flex-inline',
} %}
{# Add the "second" key with value 2 #}
{% set myArray = myArray|merge({
"second": 'tw-rounded-xl',
}) %}
{# Change the value of the "second" key#}
{% set myArray = myArray|merge({
"second": 'tw-rounded-lg',
}) %}
{#
The content of myArray is
myArray = {
"first":'tw-flex-inline',
"second":'tw-rounded-lg'
}
#}
Example of how the merge method was used in Drupal 9
{%
set classes = [
'tw-inline-flex',
'tw-items-center',
'tw-form-input',
'tw-rounded-xl',
'tw-border-gray-300',
'tw-text-gray-600'
]
%}
{% apply spaceless %}
{% if autocomplete_message %}
<div class="claroness-autocomplete">
<input{{ attributes.addClass(classes) }}/>
<div class="claroness-autocomplete__message hidden" data-drupal-selector="autocomplete-message">{{ autocomplete_message }}</div>
</div>
{{ children }}
{% else %}
<input{{ attributes.addClass(classes) }}/>{{ children }}
{% endif %}
{% endapply %}