Created
May 7, 2013 05:04
-
-
Save tyrotinal/5530366 to your computer and use it in GitHub Desktop.
railsHowTo: using application helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##Application helpers | |
Using application helps methods can be defined to simplify method callings in views. | |
First, define the helper in: | |
`app/helpers/application_helper.rb` | |
module ApplicationHelper | |
def title | |
base = "Sample app" | |
if @title.nil? | |
base | |
else | |
"#{base} | #{@title}" | |
end | |
end | |
end | |
Then in the one of the controllers define the titles for each page. For example, in the pages controller define the following: | |
`app/controllers/pages_controller` | |
class PagesController < ApplicationController | |
def home | |
@title = "Home" | |
end | |
def about | |
@title = "about" | |
end | |
end | |
and then in the view call the title method from the application helper to print the title of the page: | |
`app/views/pages/home.html.erb` | |
<h1>The tiltle is <%= title %></h1> | |
`output:` | |
The tiltle is Sample app | Home |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment