如何从 Rails 3 中的 erb.js 输出助手?
这是我在 erb.js 文件中的内容......但它不起作用:
1 //Update with a message
2 $('#follow-update').html("<%= follow_button(@question) %>")
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
助手独立工作正常,但我希望它更新我的按钮。也许有一种方法可以只更新文本而不替换整个助手?
This is what I have in my erb.js file....but it doesn't work:
1 //Update with a message
2 $('#follow-update').html("<%= follow_button(@question) %>")
follow_button is a helper:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
创建一个仅包含您的助手的部分。
例如: '/wherever/_follow_button.html.erb'
在里面,调用你的助手:
接下来,使用 JS 渲染它。
有一些方法可以提高效率,但希望这对现在有帮助。
Create a partial that holds your contains only your helper.
For example: '/wherever/_follow_button.html.erb'
Inside, call your helper:
Next, render it using JS.
There are ways to make this more efficient but hopefully this helps for now.
您将需要 escape_javascript
如果这不起作用,请参阅显示返回的 ajax 文本和按钮 html
You will need escape_javascript
If this doesn't work, please see show the returned ajax text and the button html
您无法从
js.erb
文件调用辅助方法,除非您按照 在 javascript 资源中使用 Rails 辅助方法 。例如:您也应该小心转义 HTML。
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 . For example:And you should be careful about escaping your HTML too.
抱歉,我现在无法测试,但是您是否注意过 html 安全或 javascript 转义?
例如,尝试将您的
follow_button(@question)
包含在raw()
或escape_javascript()
中?Sorry, I cannot test right now, but have you paid attention to html safe or javascript escapes?
e.g. try to enclose your
follow_button(@question)
inraw()
orescape_javascript()
?