如何将路由处理程序中所需的文件中定义的实例变量放入模板的上下文中?

时间:2022-11-15 18:51:51

Basically I have a file, foo.rb In that file, I define @bar. Then in my app.rb I have something like

基本上我有一个文件,foo.rb在那个文件中,我定义了@bar。然后在我的app.rb中我有类似的东西

get '/' do
  load 'foo.rb'
  haml :index
end

and in index.haml I try to use @bar but @bar is nil. =(

在index.haml中我尝试使用@bar但@bar是nil。 =(

Is there a way to do this? Basically, I'd like to break up code into separate files and load them within each route handler.

有没有办法做到这一点?基本上,我想将代码分解为单独的文件并在每个路由处理程序中加载它们。

1 个解决方案

#1


0  

I think, you can use 'helpers' that give you a great way to separate you business logic. In your case it would be look like this:

我想,您可以使用“帮助器”,为您提供一种分离业务逻辑的好方法。在你的情况下,它看起来像这样:

**** foo.rb ****
helpers do
  def bar
    "Hello, world!"
  end
end

**** app.rb ****
require 'sinatra'
require 'path/to/your/foo.rb'

get '/' do
  bar
end

That snippet will be rendered as html page with 'Hello, world' line.

该片段将呈现为带有“Hello,world”行的html页面。

#1


0  

I think, you can use 'helpers' that give you a great way to separate you business logic. In your case it would be look like this:

我想,您可以使用“帮助器”,为您提供一种分离业务逻辑的好方法。在你的情况下,它看起来像这样:

**** foo.rb ****
helpers do
  def bar
    "Hello, world!"
  end
end

**** app.rb ****
require 'sinatra'
require 'path/to/your/foo.rb'

get '/' do
  bar
end

That snippet will be rendered as html page with 'Hello, world' line.

该片段将呈现为带有“Hello,world”行的html页面。