簡體   English   中英

將紅寶石插值嵌入<script> tag of html string (variable)?

[英]Embed ruby interpolation into <script> tag of html string (variable)?

我正在努力將ruby插值嵌入到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}");

您能幫我正確實施嗎?

您可以將每個塊移到HTML標記之外,然后將結果簡單地存儲在字符串中,然后將字符串附加在script標記內。

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

str變量放在所需的塊中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM