Rendering Haml file in a javascript response with rails

那年仲夏 提交于 2019-12-25 08:49:22

问题


I am trying to render a haml file in a javascript response like so:

$('#<%= @email.unique_name %> .preview .mail_content').html('<%=j render( :file => "user_mailer/#{@email.key}") %>');

An example of the file that would render is:

- variables = { :contact_first_name => @contact.first_name, :user_full_name => @user.name, :user_first_name => @user.first_name }

= @email.intro_html(variables)

%p= "Please click the link below to go directly to the results of #{@user.first_name}'s assessment. You can also access an analysis of that assessment from that page."

%p= share_results_url(@token)

= @email.conclusion_html(variables)

Now two problems occur for me if we look at the javascript that is given in the response:

$('#launch_share_results .preview .mail_content').html('\u003Cp\u003EHi Jane,\u003C/p\u003E
\u003Cp\u003EJohn Smith has taken a 360(deg) \u003Cspan style=color:red;\u003E\u003Cstrong\u003ENo such variable available!\u003C/strong\u003E\u003C/span\u003E assessment through myLAUNCHtools.com and would like to share the results with you.\u003C/p\u003E
\u003Cp\u003EPlease click the link below to go directly to the results of John's assessment. You can also access an analysis of that assessment from that page.\u003C/p\u003E
\u003Cp\u003Ehttp://lvh.me:3000/assessments/results/1\u003C/p\u003E
\u003Cp\u003EThank you in advance for your time and interest in John\u0026#8217;s leadership.\u003C/p\u003E
\u003Cp\u003ESincerely,\u003Cbr /\u003E
Launch\u003C/p\u003E
');

The major problem is that the response has newlines in it. This breaks the request. I presumed using j in front of my render call would fix that, but it doesn't.

The other problem is that on the third line of the haml file I have:

#{@user.first_name}'s assessment

and that apostrophe also breaks the request. (I know this because I used a javascript function to delete all the new lines and the request was still broken until I took out that apostrophe as well)

Is there a simpler way to clean up the javascript response than chaining on javascript functions to clean it up for me?


回答1:


I experienced a similar problem. Problem exists because both methods, 'escape_javascript' and 'json_escape' are aliased as 'j' (https://github.com/rails/rails/pull/3578).

Solution: Use 'escape_javascript' instead of 'j'.



来源:https://stackoverflow.com/questions/9468425/rendering-haml-file-in-a-javascript-response-with-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!