2013-07-10 172 views
2

我正在研究一個Sinatra應用程序,並希望編寫自己的表單助手。在我的ERB文件我想用鋼軌2.3風格的語法和塊傳遞給form_helper方法:如何在沒有actionview的情況下實現form_tag helpers?

<% form_helper 'action' do |f| %> 
    <%= f.label 'name' %> 
    <%= f.field 'name' %> 
    <%= f.button 'name' %> 
<% end %>  

然後在我的簡化形式幫助我可以創建一個FormBuilder類和產生方法,如ERB塊所以:

module ViewHelpers 
    class FormBuilder 
    def label(name) 
     name 
    end 
    def field(name) 
     name 
    end 
    def button(name) 
     name 
    end 
    end 
    def form_helper(action) 
    form = FormBuilder.new 
    yield(form) 
    end 
end  

我不明白的是如何輸出周圍的<form></form>標籤。有沒有辦法在第一個和最後一個<%= f.___ %>標籤上追加文本?

+0

我建議使用[** Padrino的表單助手和/或構建器**](http://www.padrinorb.com/guides/application-helpers#form-he lpers)而不是滾動你自己的。該gem可作爲獨立插件使用,可用於任何Ruby框架。 –

+0

帕德里諾,或使用它的一部分是一個非常好的建議,我可能還沒有走這條路。我主要想確保我理解事情的一致性。 – llnathanll

回答

2

Rails不得不使用一些技巧來讓塊助手按需要工作,他們改變了從Rails 2移動到Rails 3(有關更多信息,請參閱博文Simplifying Rails Block HelpersBlock Helpers in Rails 3)。

form_for幫手Rails 2.3作品通過directly writing to the output buffer from the method,使用Rails concat方法。爲了在Sinatra中做類似的事情,你需要找到一種以同樣的方式寫給助手輸出的方法。

Erb通過創建構建輸出的Ruby代碼工作。它還允許您設置此變量的名稱,默認情況下它是_erbout(或Erubis中的_buf)。如果您將其更改爲實例變量而非局部變量(即提供一個以@開頭的變量名稱),則可以從助手訪問它。 (Rails使用名稱@output_buffer)。

Sinatra使用Tilt來渲染模板,而Tilt提供了一個:outvar選項來設置Erb或Erubis模板中的變量名稱。

這裏是如何做到這一點的示例:

# set the name of the output variable 
set :erb, :outvar => '@output_buffer' 

helpers do 
    def form_helper 
    # use the new name to write directly to the output buffer 
    @output_buffer << "<form>\n" 

    # yield to the block (this is a simplified example, you'll want 
    # to yield your FormBuilder object here) 
    yield 

    # after the block has returned, write any closing text 
    @output_buffer << "</form>\n" 
    end 
end 

有了這個(相當簡單)例如,ERB模板是這樣的:

<% form_helper do %> 
    ... call other methods here 
<% end %> 

導致生成的HTML:

<form> 
    ... call other methods here 
</form> 
+0

謝謝你的回答 - 將':outvar'設置爲一個實例變量,並寫入它是失蹤的難題。我將不得不花費一些時間來挖掘Tilt和Erb,但是這讓我開始運行。 – llnathanll

相關問題