如何从 Ruby on Rails 辅助方法返回 javascript?
我有一个注释模型,它可以包含图像链接附件(linktype =“image”或一些文本(linktype =“text))。当我显示注释时,显示方法根据链接类型而变化。一个例子是:
<% @notes.each do |q| %>
<h2 class="title"><%= q.name %></h2>
<% if q.linktype == "other"%>
<script type="text/javascript">some javascript</script>
<% elsif q.linktype == "text"%>
<%= q.text %>
<% elsif q.linktype == "image"%>
<img src="<%= q.link %>" />
<% end %>
<% end %>
我必须在站点中的几个不同视图中显示注释,因此我不想多次重复查看代码,而是希望将其放在一个位置并从不同的视图中引用它。
我最初的想法是放置。帮助程序中的显示代码,如下所示:
<% @notes.each do |q| %>
note_display(q.linktype, q.link)
<% end %>
但是某些显示涉及 javascript(第一个代码块中的第 4 行)。即使我需要它返回 javascript,我仍然可以使用它吗?感谢您的阅读。
I have a Note model, which can contain have either an image link attachment (linktype = "image" or some text (linktype = "text). When I display the notes, the method of display changes depending on the linktype. An example is:
<% @notes.each do |q| %>
<h2 class="title"><%= q.name %></h2>
<% if q.linktype == "other"%>
<script type="text/javascript">some javascript</script>
<% elsif q.linktype == "text"%>
<%= q.text %>
<% elsif q.linktype == "image"%>
<img src="<%= q.link %>" />
<% end %>
<% end %>
I have to display the notes in a few different views in my site, so rather than have to repeat the viewing code multiple times, I want to have it in one place and refer to it from different views.
My initial thought was to put the display code in a helper, something like this:
<% @notes.each do |q| %>
note_display(q.linktype, q.link)
<% end %>
But some of the displaying involves javascript (line 4 in first code block). Can I still use a helper method, even though I would need it to return javascript? If so, how do I do it? Thanks for reading.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
javascript 没有什么特别的,您可以从助手返回它,就像返回其他 html 内容一样。我唯一建议的是对标签使用帮助器,例如
There's nothing special about javascript, you can return it from helpers as you would return other html content. The only thing I would suggest is to use helpers for tags like
就 ERB 而言,JavaScript 只是字符串内容,就像模板呈现的其他内容一样。因此,您的辅助方法只需构造并返回一个字符串:
您可以使用此辅助方法:
As far as ERB is concerned, JavaScript is just string content like anything else rendered by a template. So your helper method can just construct and return a string:
You can use this helper method using: