2012-09-29 37 views
7

我有一個幫助器,我正在使用它來生成表單。用於生成表單字段的參數傳遞給幫助器。我無法弄清楚如何使用模板之外的塊。如何從助手內部使用form_tag?

例如:

def generate_form(path, fields) 
    form_tag(path, method: :get) do 
     # what do I do in here? 
    end 
end 

當我渲染塊中的​​諧音,沒有出現在渲染網頁。如果我將大量標籤(field_tag,text_field_tag等)結合在一起,那麼原始HTML將出現在頁面上。

我用Rails 3.1.0

回答

11

Rails的元素助手返回字符串,那麼你可以這樣做:

def generate_form(path, fields) 
    s = form_tag(path, method: :get) do 
    p = input_tag 
    p << submit_tag #(everything will be wrapped in form tag) 
    p #returns p from block 
    end 
    s.html_safe #returns s and avoids html escaping 
end 
+0

我不知道安全緩衝區。發生了什麼是我正在做一個字符串注入作爲初始值:fields.inject('')。我將其更改爲fields.inject(''。html_safe),現在它可以工作。 – mushroom