使用rails在javascript响应中渲染Haml文件

Posted

技术标签:

【中文标题】使用rails在javascript响应中渲染Haml文件【英文标题】:Rendering Haml file in a javascript response with rails 【发布时间】:2012-02-27 16:24:00 【问题描述】:

我正在尝试在 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 响应?

【问题讨论】:

【参考方案1】:

我遇到了类似的问题。存在问题是因为“escape_javascript”和“json_escape”这两种方法都被别名为“j”(https://github.com/rails/rails/pull/3578)。

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

【讨论】:

以上是关于使用rails在javascript响应中渲染Haml文件的主要内容,如果未能解决你的问题,请参考以下文章

在rails上渲染视图后如何获取html代码

Rails 3 原型渲染:更新响应具有 text/html 内容类型

Rails 4:部分渲染后无法使用javascript(使用ajax)

内联 Javascript 在 Rails 3.1 上重新渲染部分 ruby​​ 时无法正常工作

Rails - 格式和渲染 - 它们是如何工作的?

使用 Rails 渲染多行文本?