[英]How can I output a helper from erb.js in rails 3?
This is what I have in my erb.js file....but it doesn't work:这是我的 erb.js 文件中的内容....但它不起作用:
1 //Update with a message
2 $('#follow-update').html("<%= follow_button(@question) %>")
follow_button is a helper: follow_button 是一个助手:
20 def follow_button(resource)
21
22 type = resource.class.name
23 follow_status = current_user.following?(resource)
24
25 verb = "Follow" if follow_status == false
26 verb = "Unfollow" if follow_status == true
27
28 content_tag(:div, :class => "follow-button") do
29 link_to "#{verb} this #{type} ", follow_path(:followed_type => type,
30 :followed_id => resource.id,
31 :follow_verb => verb),
32 :class => "button",
33 :remote => true
34 end
35 end
36 end
The helper stand-alone works fine, but I want it to update my button.独立的助手工作正常,但我希望它更新我的按钮。 Perhaps there's a way to just update the text without replacing the whole helper?
也许有一种方法可以只更新文本而不替换整个助手?
Create a partial that holds your contains only your helper.创建一个包含仅包含您的助手的部分。
For example: '/wherever/_follow_button.html.erb'例如:'/wherever/_follow_button.html.erb'
Inside, call your helper:在里面,调用你的助手:
<%= follow_button(question) %>
Next, render it using JS.接下来,使用 JS 渲染它。
$('#some-id').html("<%= escape_javascript(render('/wherever/follow_button', :question => @question)) %>");
There are ways to make this more efficient but hopefully this helps for now.有一些方法可以提高效率,但希望这对现在有所帮助。
You can't call a helper method from a js.erb
file unless you explicitly include it as described in Using a Rails helper method within a javascript asset .除非您按照在 javascript 资产中使用 Rails 辅助方法中的描述明确包含它,否则您不能从
js.erb
文件调用辅助方法。 For example:例如:
<% environment.context_class.instance_eval { include ApplicationHelper } %>
And you should be careful about escaping your HTML too.你也应该小心 escaping 你的 HTML。
You will need escape_javascript您将需要 escape_javascript
$('#follow-update').html("<%= raw( escape_javascript( follow_button(@question ))) %>");
If this doesn't work, please see show the returned ajax text and the button html如果这不起作用,请参阅显示返回的 ajax 文本和按钮 html
Sorry, I cannot test right now, but have you paid attention to html safe or javascript escapes?抱歉,我现在无法测试,但是您是否注意过 html 安全或 javascript 逃逸?
eg try to enclose your follow_button(@question)
in raw()
or escape_javascript()
?例如,尝试将您的
follow_button(@question)
包含在raw()
或escape_javascript()
中?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.