0

We have the following mymodule_preprocess_node hook where we add two arrays with two key-value pairs. In twig, we would like to merge the values.

How would we merge the two arrays in twig?

Here is what we tried.

mymodule_preprocess_node

function mymodule_preprocess_node(&$variables) {
  // perform some logic.

  $variables['content']['ary']['foo'] = 'foo_value';
  $variables['content']['ary']['bar'] = 'bar_value';
}

node--article.html.twig

{% set twigAry = [] %}
{% for key, value in content.ary %}
  {$ set twigAry = twigAry|merge({ key : value }) %}
{% endfor %}

This results in twigAry only having the following. It basically prints the last key and value, which is bar and bar_value. Strangely enough, instead of setting the key to bar it results in the key being key.

[
  'key' => 'bar_value'
]

Desired Output

[ 
  'foo' => 'foo_value`, 
  'bar' => 'bar_value',
]

In the twig template, we are adding an inline <script> tag that needs to have the array in the desired output as such we need to have in this format in twig. For example, when we load the Marketo form, we want to set some values like this. Rather than hardcoding items in twig, we will just use the ['foo'] and ['bar'] from the preprocess method.

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function(form) {
    // Set the value of the Phone and Country fields
    form.vals({ "Phone":"555-555-1234", "Country":"USA"});
});

Final twig:

{% set twigAry = [] %}
{% for key, value in content.ary %}
  {$ set twigAry = twigAry|merge({ key : value }) %}
{% endfor %}

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function(form) {
  // Set the value of the Phone and Country fields
  form.vals({ twigAry });
});
  • You already have the preprocess going, why make twig do it? – Kevin Jan 23 at 4:32
  • @Kevin I have updated the question with a description on this. In general, we have an inline <script> that requires the ` { 'key' : value }`. – usernameabc Jan 23 at 18:23
1

The hash { key: value } is equivalent to { 'key': value }.

Solution:

{# key as expression (the expression must be enclosed into parentheses) #}

{ (key): value }

See https://twig.symfony.com/doc/2.x/templates.html#literals

  • that link was extremely helpful. – usernameabc Jan 23 at 18:06
1

Associative arrays must use curly brackets in Twig:

{% set twigAry = {} %}

Arrays with square brackets [] defined in Twig don't have key names

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.