简体   繁体   English

Sinatra erb文件中所有视图的变量

[英]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). 在sinatra中分配可以在所有视图(所有erb文件)上使用的变量的最佳方法是什么。

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? 我知道可以使用主文件中的全局变量(例如app.rb)来完成此操作,但是有没有更好的方法而不使用全局变量呢? eg in app.rb, i can do: 例如在app.rb中,我可以做:

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

get '/hi' do
    erb :page
end

and in index.erb and page.erb files: 以及在index.erb和page.erb文件中:

<%= @@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: 在sinatra中,这只是您的标准哈希:

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 . 您可以使用user在视图或控制器中进行访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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