0

In hook_preprocess_menu I am creating an array to send to the menu twig tpl (eventually it will be entity paragraph data but for now they are hard values as examples). However, I just receive array key invalid errors. How should this be formatted correctly for the template?

function hook_preprocess_menu__main_menu(&$vars) {

  $node = \Drupal::routeMatch()->getParameter('node');
  if($node->field_menu_highlights){
    $highlight_values = $node->get('field_menu_highlights')->getValue();

    foreach ($highlight_values as $key => $item){
      $ent = \Drupal\paragraphs\Entity\Paragraph::load($item['target_id']);
      $vars['highlight'][$key]['title'] = 'Title here';
      $vars['highlight'][$key]['desc'] = 'Description here';

    }
  }
}

The template:

{% for value in highlight %}
    {{ value }}
{% endfor %}

Error eg:

User error: "title" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).
1

Build the array with renderable children:

  $vars['highlight'][$key] = [
    'title' => [
      '#markup' => 'Title here',
    ],
    'desc' => [
      '#markup' => 'Description here',
    ],
  ];

Now the loop to render each value separately should work or have the same result by rendering the complete render array:

{{ highlight }}

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.