.js.erb文件中的转义html问题 [英] Issues with escaped html in .js.erb file
问题描述
我有一个包含以下行的.js.erb文件
$(#<%=
(<%=
escape_javascript(link_to(pluralize(@ count,'tag'),
user_tags_path(它显示
> < a href = / users / 1 / tags> 1 taga>
而不是
1标签
当我运行rails 3.0.4时,这用于工作,但现在它不会现在,米跑轨3.0.8。我发现我需要在其他地方使用 auto_link
添加 .html_safe
,否则我会得到相同的结果问题。
我如何得到它,以便它不会转义这个html?
我从来不喜欢用这样的红宝石插入你的JS。它总是会导致难以理解的毛茸茸。
相反,将数据转储为JS,然后将其作为原生JavaScript使用。
var user =<%= {
:id => current_user.id,
:path => user_tags_path(current_user),
:link_text => pluralize(@ count,'tag'),
} .to_json%>;
var link = $('< a>')。attr('href',user.path).text(user.link_text);
$('#user'+ user.id +'_following')。html(link);
在我看来,它更容易理解并完全避免HTML问题,因为HTML不是在你的ruby表达式中。
I have a .js.erb file that has the following line
$("#<%= "user#{current_user.id}_following" %>").html("<%= escape_javascript(link_to(pluralize(@count,'tag'), user_tags_path(current_user))) %>")
It displays
<a href=/users/1/tags>1 taga>
Instead of
1 tag
This used to work when I was running rails 3.0.4 but now it doesn't now that I'm running rails 3.0.8. I found that I needed to add .html_safe
in other places that I had been using auto_link
or I would get the same problem.
How do I get it so that it won't escape this html?
I never liked interpolating your JS with ruby like this. It always leads to hard to understand hairyness.
Instead, dump your data into JS on it's own as JSON, then simply use the data as native javascript.
var user = <%= {
:id => current_user.id,
:path => user_tags_path(current_user),
:link_text => pluralize(@count,'tag'),
}.to_json %>;
var link = $('<a>').attr('href', user.path).text(user.link_text);
$('#user' + user.id + '_following').html(link);
Which, in my opinion, is far more understandable and completely dodges any HTML issues since the HTML is not in your ruby expression at all.
这篇关于.js.erb文件中的转义html问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!