How to pass Ruby variables to a JavaScript function in a Rails view?

前端 未结 6 1550
一个人的身影
一个人的身影 2020-11-28 12:53

I\'m wondering what the best practice is for passing variables to JavaScript functions in a rails view. Right now I\'m doing something like:

<% content_f         


        
6条回答
  •  温柔的废话
    2020-11-28 13:26

    Note that if you aren't using escape_javascript in a view, you can include it in your ruby code like so:

    require 'action_view/helpers/javascript_helper'
    include ActionView::Helpers::JavaScriptHelper
    # escape_javascript is available here.
    

    or if that wont work for you, then copy the source of the function in to your code, if need be:

      JS_ESCAPE_MAP = {
        '\\'    => '\\\\',
        " '<\/',
        "\r\n"  => '\n',
        "\n"    => '\n',
        "\r"    => '\n',
        '"'     => '\\"',
        "'"     => "\\'"
      }
    
      JS_ESCAPE_MAP["\342\200\250".dup.force_encoding(Encoding::UTF_8).encode!] = "
"
      JS_ESCAPE_MAP["\342\200\251".dup.force_encoding(Encoding::UTF_8).encode!] = "
"
    
      # Escapes carriage returns and single and double quotes for JavaScript segments.
      #
      # Also available through the alias j(). This is particularly helpful in JavaScript
      # responses, like:
      #
      #   $('some_element').replaceWith('<%= j render 'some/element_template' %>');
      def escape_javascript(javascript)
        if javascript
          result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) { |match| JS_ESCAPE_MAP[match] }
          javascript.html_safe? ? result.html_safe : result
        else
          ""
        end
      end
    

提交回复
热议问题