Dean
Dean

Reputation: 8998

Send array to every template

I've built a simple content management system and I'm trying to build a dynamic navigation bar but the approach I've came up with is to keep sending an array of all the pages to the application template from each controller. Is there a better approach to this?

Upvotes: 0

Views: 58

Answers (2)

KARASZI István
KARASZI István

Reputation: 31477

You can create a method in your ApplicationHelper (app/helper/application_helper.rb) module and you'll reach this method from your views:

module ApplicationHelper
  def get_your_array
    # create your array here
  end
end

In your views:

<% get_your_array.each |item| -%>
  <%= item %>
<% end -%>

Upvotes: 0

deefour
deefour

Reputation: 35370

As @Amit Patel mentioned in the comments to your question, the better approach is to move the code you're referring to into the ApplicationController.

All controllers in your application extend the ApplicationController class. Any functionality you want to share amongst all controllers can be placed in this class.

As an example (since you've provided no actual code), you might set this up as a before_filter

class ApplicationController < ActionController::Base
  before_filter :build_pages_array

  # Your other ApplicationController code here...

    private

    def build_pages_array
      @pages = Page.all
    end
end

The before_filter will run for all actions in all controllers, effectively making @pages available to every template in your application.

Upvotes: 1

Related Questions