Display main menu item based on the URL I want to show main menu links in the sidebar. I have placed that menu block in sidebar region from admin side. 

But based on the current URL, i need to display that particular menu item. 

Item1 (item1)
  Item1_Sub1_item1 (item1/sublev1)
     Item1_Sub1_Sub2_item1 (item1/sublev1/subsublev1)
     Item1_Sub1_Sub2_item2 (item1/sublev1/subsublev2)
  Item1_Sub1_item2
     Item1_Sub1_Sub2_item1
     Item1_Sub1_Sub2_item2
Item 2
  Item2_Sub1_item1
     Item2_Sub1_Sub2_item1
     Item2_Sub1_Sub2_item2
  Item2_Sub1_item2
     Item2_Sub1_Sub2_item1
     Item2_Sub1_Sub2_item2



If the current url is / (home), then my menu should diplay all menu item
If the current URL (item1/sublev1) match to menu item (Item1_Sub1_item1) then only the parent and child of that menu should be displayed as below



Item1 (item1)
  Item1_Sub1_item1 (item1/sublev1)
     Item1_Sub1_Sub2_item1 (item1/sublev1/subsublev1)
     Item1_Sub1_Sub2_item2 (item1/sublev1/subsublev2)




If the current URL (item1/sublev1/subsublev1) match to menu item (Item1_Sub1_Sub2_item1) then only the parent and child of that menu should be displayed as below



Item1_Sub1_item1 (item1/sublev1)
  Item1_Sub1_Sub2_item1 (item1/sublev1/subsublev1)



I have overridden the menu--main.html.twig file using theme suggestion and using menu--main-sidebar.html.twig file to design the menu.

Any idea how to achieve this? My guess is, 


I need to create a block programmatically to do all these operations
Display that block in my html.twig.file


If I am right, how to do that in theme? If i am wrong, what else need to do?

For info I am already using Menu_block module, but I can't place block for each URL. So i want to program it.
Yeah, I think your guess is good.


Create a block programmatically: Create a custom Block. This means to create an own module with this block.
The created block should appear (when the module is activated) in your block settings, there you can add it.
The content of your block appears where you added it.


Another option, easier but not so beautiful, could be to hook in your THEME.theme. As an example you can add the menu in the  template_preprocess_html:

function template_preprocess_html(&amp;$variables) {
    $variables['my_own_menu'] = $my_own_menu;
}


Then you can use the variable {{ my_own_menu }} in your html.html.twig and do whatever you want to do.