1
  • In page--front.html.twig I load a nested twig file {% include "header.twig" {} %}
  • In header.twig I want to render my menu block

I tried the following but no result:

  • In my_theme.theme I added:
function crm_theme_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('crmnavigation');
  $variables['block_output'] = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
}
  • In header.twig I added {{ my_navigation }} but it doesn't show the menu block?
  • 1
    if you define $variables['block_output'] = xxx in preprocess page, in twig template you need add {{ block_output }}. Variable block_output is array render of menu not my_navigation. So funny :D – Jonh Jan 14 '17 at 9:06
  • thanks. In header.twig I added now {{ block_output }}, but nothing shows up? – meez Jan 14 '17 at 10:35
  • Are you sure about block id crmnavigation? – Jonh Jan 14 '17 at 10:40
  • If I go to admin/structure/block > (currently the menu block is Disabled) > click on Configure > Machine name: crmnavigation – meez Jan 14 '17 at 10:49
  • @Jonh any solution? Do you know whats going wrong? Thanks – meez Jan 14 '17 at 11:44
2

The easiest solution is to make use of twig tweaks module, Install twig tweak

drush -y en twig_tweak, 
drush cr, 

now you can place navigation anywhere. In your case inside header.twig file place

{{ drupal_block('crmnavigation') }}

You can also render entities, views and many other things. well explained here http://www.wdtutorials.com/drupal/theming/drupal-8-tutorial-43-twig-tweak-module-article-video#.WCPOxeErIyk

  • As of version 1.5 you can use drupal_menu() function. – ya.teck Feb 21 '17 at 14:04
0

There is a module that lets you do this called Simplify Menu.

In your Twig template, you make the call for the menu you want to fetch, and then wrap it in markup like so:

// Get menu items
{% set items = simplify_menu('main_navigation') %}

// Iterate menu tree
<nav class="navigation__items">
  {% for menu_item in items.menu_tree %}
    <li class="navigation__item">
      <a href="{{ menu_item.url }}">{{ menu_item.text }}</a>
    </li>
  {% endfor %}
</nav>

Although, my question still remains..

Why can't you just create a region to hold navigation, and place the block in there in the block layout?

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.