简体   繁体   中英

Variables for all views in Sinatra erb files

What is the best way to assign variables in sinatra that can be used on all views(all erb files).

I know it can be done using global variables in the main file lets say app.rb but is there a better way to do it without using global variables? eg in app.rb, i can do:

@@a = "hello"
get '/' do
    erb :index
end

get '/hi' do
    erb :page
end

and in index.erb and page.erb files:

<%= @@a %>

But is there a way to do so without using global variables or is global variables the best way to go about doing that?

Create a module with constants of all the strings/variables you want accessible. All views will have access to your modules:

module StringConstants
    LOGIN_PAGE = "Welcome to X"
    LOGOUT = "See you again soon"
end 

then in your views:

<%= StringConstants::LOGIN_PAGE %>

Session variables are usually used for cross view access. In sinatra, it's just your standard hash:

session[:whatever] = "Hello"

And that can be accessed anywhere once set. It will persist independently per user session.

For example, a common helper I use is:

# set session[:user] = user's ID when they log in

def user
  @user ||= User.get(session[:user])
end

You'd access that in your views or controllers using user .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM