2015-08-20 44 views
1

我正在努力嵌入紅寶石插值到字符串變量是一個HTML字符串。我想這聽起來有點混亂,我希望的代碼將有助於瞭解:嵌入紅寶石插入到<script>標籤的html字符串(變量)?

def devise_error_messages! 
    return '' if resource.errors.empty? 
    messages = resource.errors.full_messages 
    html = <<-HTML 
     <script type='text/javascript'> 
     toastr.options = { 
      'closeButton': true, 
      'debug': false, 
      'newestOnTop': false, 
      'progressBar': false, 
      'positionClass': 'toast-bottom-left', 
      'preventDuplicates': true, 
      'onclick': null, 
      'showDuration': '3000', 
      'hideDuration': '1000', 
      'timeOut': '5000', 
      'extendedTimeOut': '1000', 
      'showEasing': 'swing', 
      'hideEasing': 'linear', 
      'showMethod': 'fadeIn', 
      'hideMethod': 'fadeOut' 
     } 
     #{ messages.each do |m| } 
      toastr['error']("#{m}"); 
     #{end} 

     </script> 
    HTML 

    html.html_safe 
    end 

所以,你可以看到,我想遍歷messages陣列,併爲每個郵件這行的js代碼:toastr['error']("#{m}");

你能幫我正確實施嗎?

回答

1

您可以將每個塊移到HTML標記之外,並將結果存儲在一個字符串中,然後將該字符串附加到腳本標記中。

str = "" 
messages.each do |m|  
    str += "toastr['error'](" + '"' + m + '"' + '); ' 
end 

str變量放在您想要的塊中。

toastr.options = { 
    ... 
} 
#{str} 
... 
+1

感謝您的想法。出於某種原因,我甚至沒有考慮過這樣做;) –