2013-05-08 19 views
1

我有一個表單,用戶可以選擇創建更多的輸入區域(以提供更多信息)。我有一個用戶點擊的鏈接,然後創建額外的表單輸入。我想使用rails形式助手,這樣我就不必自己寫html了。我試過將表單助手直接插入到coffeescript中,並將輸出的html保存到鏈接上的數據標記中,但是我無法獲得coffeescript來執行ruby代碼,並且我正在使用data屬性轉義問題。動態插入紅寶石生成的HTML

這裏的形式:

= simple_form_for([@site, @zone]) do |f| 
    = f.error_notification 

    .form-inputs 
    = f.input :site_id 

    = label_tag "X" 
    = text_field_tag 'x_coords[]' 

    = label_tag "Y" 
    = text_field_tag 'y_coords[]' 

    = label_tag "X" 
    = text_field_tag 'x_coords[]' 

    = label_tag "Y" 
    = text_field_tag 'y_coords[]' 

    = label_tag "X" 
    = text_field_tag 'x_coords[]' 

    = label_tag "Y" 
    = text_field_tag 'y_coords[]' 

    = link_to "Add Point", "#", id: "add_point", data: { fields: label_tags } 

    .form-actions 
    = f.button :submit 

當用戶點擊 「添加點」 的鏈接,我想補充的另一個塊:

= label_tag "X" 
= text_field_tag 'x_coords[]' 

= label_tag "Y" 
= text_field_tag 'y_coords[]' 

label_tagsapplication_helper.rb

def label_tags 
    label_tag "Z" 
end 

問題是「添加點」鏈接的輸出是:

<a href="#" data-fields="<label for=" z"="">Z" id="add_point"&gt;Add Point</a> 

和引號引起的鏈接來與文本:「Z」 ID =「add_point」>添加點」

我得到的數據,從這個screencast

回答

0

對我來說簡單的解決方案是用單引號替換生成的HTML中的雙引號。在代碼:

= link_to "Add Point", "#", id: "add_point", data: { fields: label_tags.gsub("\"", "'") } 

此外,曾在輔助方法使用captureconcat

module ApplicationHelper 
    def label_tags 
    capture do 
     concat label_tag "X" 
     concat text_field_tag 'x_coords[]' 

     concat label_tag "Y" 
     concat text_field_tag 'y_coords[]' 
    end 
    end 
end 
0
屬性想法

你不能從Javascript執行Ruby代碼。當頁面被請求時,所有嵌入式ruby都會被評估,結果就是你所得到的。我可以從你的貼上看到的問題是你的標籤塊在正確的數據屬性中,但它不會被轉義。

你需要做的就是將生成的HTML中的引號轉義進入該字段,然後通過Javascript忽略它們。你可以使用html_escape喜歡這裏:data: { fields: h(label_tags) }hhtml_escape一個別名,或者你可以自己做,手動

def escape(str) 
    str.gsub(/</, "&lt;").gsub(/>/, "&gt;").gsub(/"/, "&quot;") 
end 

# later in the view for the form 
data: { fields: escape(label_tags) } 

然後你的CoffeeScript會點擊處理想:

function unescape(str) { 
    return str.replace(/((?:&lt;)|(?:&gt;)|(?:&quot;))/g, function($1) { 
    switch($1) { 
     case "&gt;": 
     return ">"; 
     case "&lt;": 
     return "<"; 
     case "&quot;": 
     return '"'; 
    } 
    }); 
} 

$("a").on("click", function() { 
    var html = unescape(this.data("fields")); 
    $(".the-place-to-put-it").html(html); 
}); 

我做毫無疑問,存在一個更好的解決方案,並且在發佈這個答案時,我還沒有測試過它的工作原理(理論上它應該)。理想情況下,您應該在Javascript中使用jQuery生成元素,而不是依賴此方法來完成此操作 - 是的,它是ruby和Coffee之間重複的代碼。

+0

你是對的,這是逃逸引號的問題。我發現了一個簡單的'gsub(「\」「,」'「)'做了我所需要的。感謝這個想法 – 2013-05-09 14:53:08