Skip to content

Dynamic Navigation Items

andi edited this page Oct 18, 2010 · 11 revisions

There might be several occasions where the content of the navigation is not static but should be dynamically loaded. Examples for this would be a CMS which has dynamic pages or a user who can specify it’s own navigation etc…

In such circumstances you can provide the navigation items dynamically in the render_navigation call, i.e. in your view call:

render_navigation :items => @my_items

@my_items is an array of the navigation items to be displayed. An item can either be an object or a hash. An item has to respond to the following methods (or needs the following keys if it’s a hash) – similar to the stuff you would provide for static items in the navigation config file:

  • key – the item’s key
  • name – the item’s name (that gets rendered)
  • url – the target url of the item

and optionally

  • options – all the options for the item
  • items – the item’s subnavigation items (again, an array of either objects or hashes)

Example using an array of hashes

@my_items = [
  {:key => :main, :name => 'Main', :url => '/main', :options => {your options here}, :items => [
    {:key => :sub1, :name => 'Submenu 1', :url => '/sub1'},
    {:key => :sub2, :name => 'Submenu 2', :url => '/sub2'}
  ]}, {...next primary item...}
]

How you generate that hash is completely up to you. The most common way will be that you have a models that you can extract that information from. As stated above, if you have objects/models that already respond to those methods, you don’t have to convert them into a hash.

Mixing static and dynamic content

If you would like to mix static and dynamic menu content, you have to provide ALL the items dynamically and mix the static content into the items yourself.

Clone this wiki locally