0

I am trying to split my HAML view to the separate files. I have read the Sinatra Book and tried to implement the basic version.

So I have created app_helpers.rb file:

# Usage: partial :foo
helpers do
  def partial(page, options={})
    haml page, options.merge!(:layout => false)
  end
end

And require it in my application.rb:

require 'sinatra'
require_relative './app_helpers.rb'

Then I have created partial views/test.haml:

<h3> Test message </h3>

And require it in my index.haml:

= partial :test

But when I refresh my page I get the error message:

NoMethodError - undefined method `partial' for #<Application:0x514dbe0>:
        c:/Dropbox/development/myprojects/test/sinatra-bootstrap/views/index.haml:27:in `evaluate_source'
        C:/Ruby193/lib/ruby/gems/1.9.1/gems/tilt-1.3.3/lib/tilt/template.rb:209:in `instance_eval'
        C:/Ruby193/lib/ruby/gems/1.9.1/gems/tilt-1.3.3/lib/tilt/template.rb:209:in `evaluate_source'
        C:/Ruby193/lib/ruby/gems/1.9.1/gems/tilt-1.3.3/lib/tilt/template.rb:144:in `cached_evaluate'
        C:/Ruby193/lib/ruby/gems/1.9.1/gems/tilt-1.3.3/lib/tilt/template.rb:127:in `evaluate'
        C:/Ruby193/lib/ruby/gems/1.9.1/gems/tilt-1.3.3/lib/tilt/haml.rb:24:in `evaluate'
        C:/Ruby193/lib/ruby/gems/1.9.1/gems/tilt-1.3.3/lib/tilt/template.rb:76:in `render'
        C:/Ruby193/lib/ruby/gems/1.9.1/gems/sinatra-1.3.1/lib/sinatra/base.rb:625:in `render'
        C:/Ruby193/lib/ruby/gems/1.9.1/gems/sinatra-1.3.1/lib/sinatra/base.rb:522:in `haml'

How can I fix it?

Updated:

All works fine if I rewrite app_helpers.rb such way:

def partial(page, options={})
    haml page, options.merge!(:layout => false)
end

What is the reason of this?

4

2 回答 2

1

Sinatra partials 在FAQs中有一个很好的部分。有一个要点,其中包含您需要创建的文件。然而,他们现在创建了一个 gem Sinatra-Partial

我的建议是将此 gem 用于局部(Sinatra-Partial)。

于 2012-04-11T10:30:24.987 回答
0

无法重现:

C:\test>cat views\layout.haml
%body= yield

C:\test>cat views\index.haml
#main=partial :test

C:\test>cat views\test.haml
%h3 Hello World

C:\test>cat test_partial.rb
require 'sinatra'
require 'haml'

helpers do
  def partial(page, options={})
    haml page, options.merge!(:layout => false)
  end
end

get '/' do
  haml :index
end

c:\test>ruby -v
ruby 1.9.2p180 (2011-02-18) [i386-mingw32]

C:\test>curl http://127.0.0.1:4567/
<body><div id='main'><h3>Hello World</h3></div></body>

但是,正如@Konstantin 所指出的,partials从 Sinatra 1.1.0 开始不再需要使用自定义方法。如果我更改index.haml为 just#main=haml :test并删除该partials方法,则输出是相同的。

在早期版本的 Sinatra 中,您会看到以下输出:

<body><div id='main'><body><h3>Hello World</h3></body></div></body>
于 2012-04-09T21:54:46.620 回答