Skip to content

Adding a dynamic sidebar in a layout

Michel Blanc edited this page Feb 11, 2014 · 5 revisions

Sometimes you need to render a dynamic sidebar in your layout. The best way to achieve this is probably writing a Helper. By using a helper, your layouts will stay clean, won't be cluttered with too much code and will be easier to maintain.

module Ramaze
  module Helper
    module SideBar

      def generate(current=nil)
        # Generate some HTML that will make the side bar
        sidebar = "<div class='sd'><h1>This is a sidebar</h1>"
        sidebar<< "<ul>"
        sidebar<< "<li>First item</li>"
        sidebar<< "<li>Second item</li>"
        sidebar<< "</ul></div>"

        sidebar
      end

    end
  end
end

Note that we have written HTML manually, but could have used gestalt for this task too.

To activate your helper, you have to set it in at least one controller :

class Controller < Ramaze::Controller
  layout :default
  helper :sidebar
  ....

This way, Ramaze will take care of loading your helper class automatically. Then, in your layout, you just have to call your Sidebar#generate method :

    <div class="sidebar-nav">
      #{generate}
    </div>
Clone this wiki locally