简体   繁体   中英

Rendering a partial and escaping the html/javascript for a bookmarklet

I am trying to build a bookmarklet that makes a request to an action in localhost and displays a div with the html taken from the js response from localhost. I can make the request just fine, but when the js returns I have "undefined" in console. I tried debugging it using binding.pry and I saw that the content is not evaluating properly. This is how I tried evalauting it:

content = "<%= escape_javascript(render(:partial => 'events/bookmarklet').html_safe) %>";

In the binding.pry console I get the following response:

content = eval("<%= escape_javascript render(:partial => 'events/bookmarklet') %>");                                                                                  
SyntaxError: (eval):1: syntax error, unexpected '<'
<%= escape_javascript render(:partial => 'events/bookmarklet') %>
 ^
(eval):1: syntax error, unexpected ')', expecting end-of-input
<%= escape_javascript render(:partial => 'events/bookmarklet') %>
                                                              ^
from (pry):12:in `eval'

I don't know why you try to eval something if I understand what you want to do correctly.

Use json and render_to_string if you want to pass html by javascript. So for your example:

# controller
def action_name
  content =
    render_to_string(
      partial: 'events/bookmarklet',
      formats: [:html], # always render html format, even if request wants json
      layout: false # render only partial, without any layout
    )

  render json: { html: content }
end

You can access the content in javascript by data.html then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM