Skip to content

Instantly share code, notes, and snippets.

@acobster
Created February 18, 2016 17:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acobster/1545161136b1da584c5f to your computer and use it in GitHub Desktop.
Save acobster/1545161136b1da584c5f to your computer and use it in GitHub Desktop.
Extending TimberMenu
<?php
/**
* Custom Menu class to add special nav behavior on top of
* TimberMenu instances.
*
* Context: https://github.com/jarednova/timber/issues/808
*/
class CustomMenu extends \TimberMenu {
public $MenuItemClass = '\CustomMenuItem';
}
<?php
/**
* Custom MenuItem class for adding special nav behavior to
* TimberMenuItem instances
*/
class CustomMenuItem extends \TimberMenuItem {
public function get_post() {
// Only want to look associated posts for items that are actually linked to posts,
// as opposed to custom link-type items...
if( $this->type === 'post_type' ) {
return new \TimberPost($this->object_id);
}
}
}
<nav class="side-nav level1">
<ul class="menu">
{% for item in menu.get_items() %}
<li class="{{ item.classes | join(' ') }}">
{# now you can access the associated post via the item.get_post() method: #}
<a href="{{ item.get_path }}">{{ item.get_post().get_field('whatever') }}</a>
</li>
{% endfor %}
</ul>
</nav>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment