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 });
});
<script>
that requires the ` { 'key' : value }`.