2010-02-24 103 views
1

在Sinatra的應用程序,包括局部模板

require 'rubygems' 
require 'sinatra' 
require 'haml' 

get '/new' do 
    haml :new 
end 

get '/edit' do 
    haml :edit 
end 

__END__ 

@@ layout 
%html 
    %head 
    %title 
    %body 
    = yield 

@@ _form 
# partial form 

@@ new 
%h1 Add a new item 
# require partial _form 

@@ edit 
%h1 Edit an existing item 
# require partial _form 

如何要求@@ new@@ edit部分@@ _form模板?

謝謝。

回答

3

你看過這個嗎:http://www.sinatrarb.com/faq.html#partials

我創建了app_helpers.rb並在我的主應用程序文件中需要它。 app_helpers包含此方法:

def partial(template, *args) 
    options = args.last.is_a?(Hash) ? args.pop : { } 
    options.merge!(:layout => false) 
    if collection = options.delete(:collection) then 
     haml_concat(collection.inject([]) do |buffer, member| 
      buffer << haml(template, options.merge(
            :layout => false, 
            :locals => {template.to_sym => member} 
           ) 
        ) 
     end.join("\n")) 
    else 
     haml_concat(haml(template, options)) 
    end 

在我的意見,我使用:只需https://github.com/yb66/Sinatra-Partial

在您的代碼,您:

- partial :file 
+0

好工作Brian,謝謝! – Amyth 2012-07-25 19:18:02

1

我會建議西納特拉,部分插件需要:安裝gem'gem install sinatra-partial'

需要部分IAL在您的代碼:「需要‘西納特拉/部分’

改變你的代碼如下:

@@ new 
%h1 Add a new item 
= partial '_form' 

@@ edit 
%h1 Edit an existing item 
= partial '_form' 

,如果你想添加一些參數到_form部分,你可以用當地人將它傳遞:

= partial '_form', locals: { param: @param } 
1

如果使用西納特拉,爲什麼不使用它內置的HAML方法,像這樣:

= haml :partial_form, layout: false 

導軌:

= render 'partial_form'