开发者

How can I return javascript from a Ruby on Rails helper method?

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 de开发者_如何学运维pending 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.


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

image_tag(q.link)
javascript_tag("some javascript")
content_tag("h2", q.name, :class => "title")


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:

def note_display(note)
  content = ''
  content << content_tag('h2', h(note.name), :class => 'title')
  if note.linktype == 'other'
    content << javascript_tag("some javascript")
  elsif note.linktype == 'text'
    content << h(note.text)
  elsif note.linktype == 'image'
    content << image_tag(note.link)
  end  
  content
end

You can use this helper method using:

<% @notes.each do |n| %> 
  <%= note_display(n) %>
<% end %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜