The markup for navigation menus can be a real chore. It’s very easy to let the markup get incredibly complicated with loops and ifs.
Wordpress menus provide a sizeable amount of functionality, but out of the box to even start to get a handle on things you’re going to have to use a navwalker class. However, creating your front-end markup inside of PHP is always a big no-no in my book.
Therefore, your complicated menu… could still end up being a complicated menu, just in Twig. While Twig gives you a lot to do, it’s still easy to get caught up in for loops and if statements and just end up with a mess of a Twig file. We’ve all been there.
I decided to solve that on a project at Base this week by going back to basics on a TimberMenu and moving to Macros. These files should give you everything you need to immediately drop a simple navigation into your theme and customise the classes. These Macros harness the full power of TimberMenus to provide a full nested navigation instantly ready for styling.
I’m using SmartMenus to provide a lot of the functionality in this instance, but the implementation of your menu is irrelevant in this scenario. By tweaking the classes on elements, you can alter the menu to your heart’s content.
All this does is provide clean, usable markup with all the relevant classes from Wordpress for you to style up with CSS. Exactly what good markup should do.
Add this line to your
add_to_context function in Timber, where
'menu' is your Wordpress nav (created with
$context['primary_menu'] = new TimberMenu('menu');
nav_macros.twig into your views. In your template files, import that file and call
nav.menu. There’s an example of that in
Here’s the files: