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).
2
  • try value.title Commented Sep 12, 2017 at 7:47
  • thanks, but the error still persists Commented Sep 12, 2017 at 7:53

1 Answer 1

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 and acknowledge you have read our privacy policy.

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