使用rails在javascript响应中呈现Haml文件

Rendering Haml file in a javascript response with rails

本文关键字:Haml 文件 响应 rails javascript 使用      更新时间:2023-09-26

我正试图用javascript响应来呈现一个haml文件,如下所示:

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

将要渲染的文件的示例是:

- 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)

现在,如果我们查看响应中给出的javascript,我会遇到两个问题:

$('#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
');

主要问题是响应中有换行符。这会中断请求。我认为在渲染调用之前使用j可以解决这个问题,但事实并非如此。

另一个问题是在haml文件的第三行:

#{@user.first_name}'s assessment

而这个撇号也破坏了请求。(我知道这一点是因为我使用了一个javascript函数来删除所有新行,直到我也去掉了撇号,请求仍然被破坏)

有没有比链接javascript函数为我清理javascript响应更简单的方法?

我遇到了类似的问题。存在问题,因为"escape_javascript"answers"json_eescape"这两个方法都别名为"j"(https://github.com/rails/rails/pull/3578)。

解决方案:使用"escape_javascript"而不是"j"。